I just have learned that there is a problem with generic types in Java. The problem occurs if I want to write a method that uses a generic class. With the explicit specification of a type I will lose the flexibility that generic classes offer to me. I also cant use "Object" for the generic data type in the Method. But why not? "Object" is the basic class of every class in Java and this language has polymorphism so why this doesnt work?
Own Example to demonstrate:
Triplet.java
public class Triplet <T> {
public T a, b, c;
Triplet(T a, T b, T c) {
this.a = a;
this.b = b;
this.c = c;
}
}
Main.java
public class Main {
public static void main(String[] args) {
Triplet<String> triplet = new Triplet<>("Hello", "Guten Tag", "Bonjour");
printPartsOfTriplet(triplet);
}
static void printPartsOfTriplet(Triplet<Object> triplet) {
System.out.println(triplet.a);
System.out.println(triplet.b);
System.out.println(triplet.c);
}
}
Error Message
Main.java:4: error: incompatible types: Triplet<String> cannot be converted to Triplet<Object>
printPartsOfTriplet(triplet);
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error