1.一个基类的引用类型变量可以“指向”其子类的对象
2.一个基类的引用不可以访问其子类对象新增加的成员属性和方法
3.可以使用 【引用变量 instanceof? 类名】来判断该引用变量所指向的对象时候属于该类或该类的子类
4.子类的对象,可以当做基类的对象来使用,称作向上转型(upcasting),反之称为向下转型(downcasting)
?
class Animal { private String name; Animal(String name) {this.name = name;} public void enjoy(){ System.out.println("叫声......"); } } class Cat extends Animal { private String eyesColor; Cat(String n,String c) {super(n); eyesColor = c;} public void enjoy() { System.out.println("猫叫声......"); } } class Dog extends Animal { private String furColor; Dog(String n,String c) {super(n); furColor = c;} public void enjoy() { System.out.println("狗叫声......"); } } class Bird extends Animal { Bird() { super("bird"); } public void enjoy() { System.out.println("鸟叫声......"); } } class Lady { private String name; private Animal pet; Lady(String name,Animal pet) { this.name = name; this.pet = pet; } public void myPetEnjoy(){pet.enjoy();} } public class Test { public static void main(String args[]){ Cat c = new Cat("catname","blue"); Dog d = new Dog("dogname","black"); Bird b = new Bird(); Lady l1 = new Lady("l1",c); Lady l2 = new Lady("l2",d); l1.myPetEnjoy(); l2.myPetEnjoy(); } }
?