1、规则
(1)基类(父类)的引用类型变量可以指向其子类对象;(向上转型)
(2)基类的引用不可以访问其子类对象新增加的成员(属性和方法);
(3)可以使用“引用变量 instanceof 类名”来判断该引用变量所指向的对象是否属于该类(或该类的子类);
(4)子类对象可以当做基类对象来使用,即基类引用指向子类对象,是向上转型(upcasting);反之,向下转型(downcasting)。
例1:
public class TestAnimal{ public static void main(String args[]){ Animal a=new Animal("name"); Dog d=new Dog("dogname","black"); Cat c=new Cat("catname","blue"); System.out.println(a instanceof Animal);//true System.out.println(d instanceof Animal);//true System.out.println(c instanceof Cat);//true System.out.println(a instanceof Cat);//false a=new Dog("bigyellow","yellow");//父类引用指向子类对象(向上转型) System.out.println(a.name);//bigyellow //System.out.println(a.furColor);//编译错误:找不到符号!规则(2) System.out.println(a instanceof Animal);//true System.out.println(a instanceof Dog);//true!!! Dog d1=(Dog) a;//强制转换符(向下转型) System.out.println(d1.furColor);//yellow //Cat c1=(Cat) a;//运行时抛异常!java.lang.ClassCastException:Dog cannot be cast to Cat } } class Animal{ public String name; Animal(String name){ this.name=name; } } class Dog extends Animal{ public String furColor; Dog(String name,String furColor){ super(name); this.furColor=furColor; } } class Cat extends Animal{ public String eyesColor; Cat(String name,String eyesColor){ super(name); this.eyesColor=eyesColor; } }
例2:对象转型带来的可扩展性方面的好处
public class TestAnimal{ public static void main(String args[]){ TestAnimal test=new TestAnimal(); Animal a=new Animal("name"); Dog d=new Dog("dogname","black"); Cat c=new Cat("catname","blue"); test.f(a); test.f(c); test.f(d); } public void f(Animal a){ System.out.println("name:"+a.name); if(a instanceof Cat){ Cat c1=(Cat) a; System.out.println(" "+c1.eyesColor+" eyes"); } else if(a instanceof Dog){ Dog d1=(Dog) a; System.out.println(" "+d1.furColor+" fur"); } } } class Animal{ public String name; Animal(String name){ this.name=name; } } class Dog extends Animal{ public String furColor; Dog(String name,String furColor){ super(name); this.furColor=furColor; } } class Cat extends Animal{ public String eyesColor; Cat(String name,String eyesColor){ super(name); this.eyesColor=eyesColor; } }