1

I have simple generic parent class and suppose I have a list in this class:

public class GenericParent<N extends Number> {
protected List<String> s;
}

And also I have a child class that extend from this class like this:

public class GenericChild extends GenericParent {

    private void testMethod() {
        for (String o : s) {
            //.....
        }
    }
}

I get Incompatible types in this line for (String o : s) and tell me that s is not String, it is object. but if I define my child class like this public class GenericChild extends GenericParent<Integer> and declare my generic type, error goes away. Why this happened? My question is not about what is the raw type and generic class. I define List of String in class that have generic type of Number and I don't get it why in child class I can't use my list of String that defined in parent.

Saber Solooki
  • 1,182
  • 1
  • 15
  • 34
  • GenericParent is a raw type. References to generic type GenericParent should be parameterized. https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it – JYun Feb 18 '18 at 06:05
  • When a raw type is used, the constructors, instance methods and non-static fields are also erased. – JYun Feb 18 '18 at 06:11
  • @JYun I don't get it. Could you please explain me more? – Saber Solooki Feb 18 '18 at 06:19
  • I use independent field type from what parent class get. Generic type for class is Number and my field is list of String. These to type is completely different from each other. – Saber Solooki Feb 18 '18 at 06:21
  • 2
    Yes, but if you read to the part about type erasure for non-static fields in my link, it explains it – JYun Feb 18 '18 at 06:31
  • Oh my god, thank you so much – Saber Solooki Feb 18 '18 at 06:38

0 Answers0