+ 2
What if child class is not generic but parent class is generic in java. Then Child c = new Parent<String>(); is correct?
2 Respuestas
+ 1
You cannot initialize a parent class as an instance of a child class. Only a child class can be an instance of the parent class.
If you are wondering about what would happen if you tried Parent<String> c = new Child(); you would have no problem with that because the generic type is assigned to the behavior of the parent class. Also even if generic parameters are available for a class, they don't have to be used. For example, you can instantiate an instance of java.util.List with no generic type.
List myList = new ArrayList();
In this case, the generic type of the List class and the child class ArrayList default to the Object class.
+ 1
TYPE extends Object (as default), so Child access Object type
class Parent<TYPE> { TYPE v; }
class Child extends Parent {}
class Program {
public static void main(String[] args) {
var c = new Child();
c.v = "string";
//System.out.println( c.v.length() ); // error
System.out.println( ((String) c.v).length() );
}
}