Generics

5 0 0
                                    

Generics is used to enable types as a parameters in classes, interfaces or methods. This means that you are already specifying what type you want for example the method to use in its parameter. In this way, the compiler can inform you of an error type before running the program. And also, since the type was already specified, there is no need for type casting.

Definition:

class Name<T>{ //...statements; }

Note: The angle brackets with a type variable inside it indicates the generic type you can use. The type variable can be any non-primitive type.

=================

class YourClass<T, V> {
private T t;
private V v;
private void setT(T t1){
t = t1;
}
private T getT(){
return t;
}
private void setV(V v1){
v = v1;
}
private V getV(){
return v;
}

public static void main(String[] args) {
YourClass<String, Integer> yourClass = new YourClass<>();
yourClass.setT("Hello");
yourClass.setV(1);

System.out.println("Key: " + yourClass.getV());
System.out.println("Value: " + yourClass.getT());
}
}

=================

Result:

Key: 1Value: Hello


Note: In setV(1) method, it should be an Integer and not a primitive int only but in this case, the compiler can distinguished the value int and then automatically wrap it in box Integer.



Java ProgrammingWhere stories live. Discover now