import java.util.*;
class SampleA { }
class SampleB extends SampleA{ }
class SampleC extends SampleA{ }

class VectorDemo {
    public static void main(String r[]) {
        Vector<SampleA> v = new Vector<SampleA>();
        v.add(new SampleB());
        v.add(new SampleC());
        SampleC rect = v.get(2);

The output says "Incompatible types. Found SampleA, required SampleC. SampleC rect = v.get(2);"

My doubt is first of all isn't this like using Wildcard where instead of saying Vector<? extends SampleA> v, we mentioned it a form of Vector<Type> v, which is one of the rules of Wild card which says if only <Type> is mentioned then it can accept only that type and no sub or super type. So why is SampleB and SampleC accepted?

Second, although it's accepted, why v.get(2) is not returning SampleC. Infact writing v.get(1) also gives same error! Why not return SampleB for v.get(1) and SampleC for v.get(2)?

Help please. Thanks.

Recommended Answers

All 3 Replies

by having the generic type being SampleA, you specifically make it a SampleA, so, yes, you can have problems casting it back. SampleB and C are acceptec, because they actually are SampleA. all the stuff that these classes add to the mix, is being let out since they are transformed into a SampleA on adding in the list(which explains the error). Basically, you strip your instances, and all extra information that comes from the SampleB or SampleC class is left behind.

Sorry stultuske, but I found your reply very confusing. Once you create an instance of some concrete class that instance can never change its type. A SampleB can be added to a Vector<SampleA> because SampleB is a subclass of SampleA. But nothing is "stripped from the instance", and a SampleB can never be "transformed" into a SampleA. That instance is still a SampleB with all the extra info that a SampleB has.

What's happening here is that the compiler doesn't know at compile time whether any particular element in the Vector is going to be a SampleA, B, or C. All the compiler knows is that all the elements of v are SampleA.
You then try to assign a value from v to a variable of type SampleC. Not all SampleA's are SampleC's, so the types are incompatible.

commented: nyes, should 've chosen my words much better. probably the reason I never became a teacher :) +14

Got it guys thanks :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.