[英]what is the difference between a java class inheritance and javabean inheritance?
[英]What's the difference between contravariance and inheritance in Java?
我有一個父 class A 和它的子 class B。這兩個片段之間有什么區別:
public static void main (String[] args) {
ArrayList<? super A> e = new ArrayList<>();
B thing = new B();
e.add(thing);
System.out.println(e.get(0));
}
public static void main (String[] args) {
ArrayList<A> e = new ArrayList<>();
B thing = new B();
e.add(thing);
System.out.println(e.get(0));
}
ArrayList<? super A>
ArrayList<? super A>
和ArrayList<A>
是前者可以分配一個 object 的ArrayList<T>
其中T
是A
或A
本身的超類。
具體來說,這是有效的:
ArrayList<? super A> listOfSuperA = new ArrayList<Object>();
這不是:
ArrayList<A> listOfA = new ArrayList<Object>();
這意味着您可以從listOfA
和listOfSuperA
中獲取不同類型的值:
A a = listOfA.get(0); // valid
Object o = listOfA.get(0); // valid, because A can be converted to Object.
A a2 = listOfSuperA.get(0); // invalid, because listOfSuperA could contain Objects, which are not convertible to A
Object o2 = listOfSuperA.get(0); // valid, because whatever is in listOfSuperA, it can be converted to Object
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.