1.一個基類的引用類型可以指向其子類的對象
2.一個基類的引用指向子類的對象時不可以訪問其子類對象新增加的成員(屬性和方法) 比如,一隻狗繼承動物類,如果將狗當成動物傳入,那麼狗局不能訪問自己獨有的成員,只能當成動物來用
3.可以引用 變量 instanceof 類名 來判斷該引用變量所指向的對象是否屬於該類或該類的子類
4.子類對象可以當做基類對象來使用,稱爲向上轉型(upcasting),反之,稱爲向下轉型(downcasting0
class Animal {
public String name;
Animal(String name) {
this.name = name;
}
}
class Cat extends Animal {
public String eyesColor;
Cat(String n,String c) {
super(n);
eyesColor = c;
}
}
class Dog extends Animal {
public String furColor;
Dog(String n,String c) {
super(n);
furColor = c;
}
}
public class TestAnimal {
public static void main(String[] args) {
Animal a = new Animal("name");
Cat c = new Cat("catname", "blue");
Dog d = new Dog("dogname", "black");
System.out.println(a instanceof Animal);//true
System.out.println(c instanceof Animal);//true
System.out.println(d instanceof Animal);//true
System.out.println(a instanceof Cat);//false
a = new Dog("bigyellow", "yellow");
System.out.println(a.name);
//System.out.println(a.furColor);
System.out.println(a instanceof Animal);
System.out.println(a instanceof Dog);
Dog d1 = (Dog)a;
System.out.println(d1.furColor);
}
}