What if child class is not generic but parent class is generic in java. Then Child c = new Parent<String>(); is correct? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

What if child class is not generic but parent class is generic in java. Then Child c = new Parent<String>(); is correct?

18th Oct 2019, 1:24 PM
Smit Kalkani
Smit Kalkani - avatar
2 Answers
+ 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.
19th Oct 2019, 12:18 AM
Brian R
Brian R - avatar
+ 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() ); } }
19th Oct 2019, 2:33 AM
zemiak