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);
}
}