简体   繁体   中英

Wildcards and Subtyping on Java

I just started studying Wildcards and Subtyping on Java and try to test what I learn.

Suppose:

Class A { public int y=1; }
Class B extends A { public int x=2; }

In main:

List<B> lb = new ArrayList<>();
lb.add(new B());
System.out.println(lb.get(0).y); //Displays member y of Class A
List<? extends A> la = lb;
System.out.println(la.get(0).y); //Can access member y of Class A

List<A> la1 = new ArrayList<>();
la1.add(new A());
System.out.println(la1.get(0).y); //Displays member y of Class A
List<? super B> lb1 = la1;
System.out.println(lb1.get(0).y); //Cannot access member y of Class A? Why?

I don't understand why I cannot access the member y using Lower Bounded Wildcards while it is possible using Upper Bounds Wildcards. Am I missing something?

Consider

Interface X { ... }
Class A { public int y=1; }
Class B extends A implements X { public int x=2; }

List<? super B> lb1 = la1;

Now, the objects in lb1 could be completely unrelated to A and B as long as they implemented X . There's no way for the compiler to know that lb1.get(0) has a member y .

A more "concrete" example:

Class X { ... }
Class A extends X { public int y=1; }
Class B extends A { public int x=2; }

With this hierarchy objects in lb1 could be of type X which has no member y .

Upper bound of U : Has to be at least a U . Anything U has, you can use.

Lower bound of L : Can be at most L (while staying in its hierarchy), but there's no guarantee that it will be.

In simpler words, you cannot get 'TYPE' from a list which is constructed using keyword 'SUPER'..

System.out.println(lb1.get(0).y); // This wrong as you are expecting type A / B

I guess, the following should work

System.out.println(((A)(lb1.get(0))).y);

As you can only get an OBJECT out of this list... you need to cast it to get your 'TYPE'

只需更新行

((A)lb1.get(0)).y

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM