0

It is about inheritance.
Now I have two classes,

  1. Super Class

    public class TestSuper {}
    
  2. Sub Class

    public class TestSub extends TestSuper{
    
        private TestSub testSub;
        private List<TestSub> testSubList;
    
        public TestSuper getTestStub(){
            return testSub;
        }
    
        public List<TestSuper> getTestStubList() {
            //compile error here
            return testSubList;
        }
    }
    

I can NOT return testSubList, the error is Type mismatch: cannot convert from List<TestSub> to List<TestSuper>. But why can I return testSub?

xuanzhui
  • 1,300
  • 4
  • 12
  • 30
  • `List` is not a subtype of `List` so naturally you cannot return it. If you have a "classroom for kids" and return it from a method which returns a "classroom", then you could add an adult to the classroom. – Marko Topolnik Aug 19 '15 at 08:27
  • This question is not about inheritance it is about Generics.. – Kandy Aug 19 '15 at 09:04
  • You could try using List extends TestSuper> this should allow your cast to work – CarefreeCrayon Aug 19 '15 at 11:00

1 Answers1

0

You cannot explicitly cast from List< A > to List< B >. You must iterate and cast each element individually.

public List<B> castAList(List<A> aList){

    List<B> bList = new ArrayList<>();

    for(A a : aList){
       bList.add((B) a);
    }

    return bList;
}

Another solution is to explicitly declare the inheritance within the generics by taking advantage of the wildcard ?

List<? extends SuperClass> superList
CarefreeCrayon
  • 249
  • 2
  • 7