【发布时间】:2015-12-10 14:28:25
【问题描述】:
为什么声明 1 有效,即使声明 2 无效。声明2无效的原因我可以理解,但为什么相同的原则不适用于声明1?
import java.util.*;
public class CollectionTest
{
public static void main(String[] args)
{
ArrayList<ObjectB> test = new ArrayList<ObjectA>(); //statement 1
ObjectB B = new ObjectA("aaa");//statement 2
}
}
class ObjectA
{
String a;
ObjectA(String str) {
a = str;
}
}
class ObjectB extends ObjectA
{
String b;
ObjectB(String str) {
super(str);
b = str;
}
}
【问题讨论】:
-
您正在比较两个(无效)不同的东西。如果你想做类比,你应该这样定义你的数组列表:
ArrayList<ObjectB> test = new ArrayList<ObjectB>();