为什么一个对象只能使用编译时类型才有的方法呢
就像List arrayList_1 = new ArrayList();
Collection arrayList_2 = new ArrayList();同是ArrayList类,只有arrayList_1才可以用public E get(int index)方法
就像List arrayList_1 = new ArrayList();
Collection arrayList_2 = new ArrayList();同是ArrayList类,只有arrayList_1才可以用public E get(int index)方法
public static void main(String[] args) {
Person person = new Person();
Person student = new Student();
person.show();
student.show();
}
}class Person {
public void show() {
System.out.println("person.show()");
}
}class Student extends Person{
public void show() {
System.out.println("student.show()");
}
}运行结果:
person.show()
student.show()
List接口中有get()方法.Collection接口中都没有定义这个方法,你怎么使用啊?
Collection arrayList_2 = new ArrayList();arrayList_1 和arrayList_2 都是ArrayList的上转型对象,对于上转型的对象只能调用父类或接口中的方法。
把arrayList_1上转型List,那么arrayList_1就只能调用List接口中的方法了。
同理,arrayList_2 就只能调用Collection 接口中的方法了。而Collection 接口中没有定义get()方法,所以arrayList_2 不能调用get()方法。