JAVA基础-- 对象转型 (casting)

1. 一个基类的引用类型变量可以指向其子类的对象:

   

 a=new Dog("bigyellow","yellow");

  

2. 一个基类的引用不可以访问其子类对象新增加的成员(属性和方法)

System.out.println(a.furname); // error

  

3. 可以使用引用变量instanceof类名来判断该引用型变量所指向的对象是否属于该类或者该类的子类:

System.out.println(a instanceof Animal);  //true
System.out.println(a instanceof Dog);  //true

  

4. 子类的对象可以当做基类的对象来使用称作向上转型(upcasting), 反之成为向下转型(downcasting)

a=new Dog("bigyellow","yellow");  //向上转型
Dog d1=(Dog) a;   //向下转型

  

Animal a=new Animal("name");
Dog d=new Dog("dogname","black");

a=new Dog("bigyellow","yellow");
System.out.println(a.name); // bigyellow
System.out.println(a.furname); // error
System.out.println(a instanceof Animal); //true
System.out.println(a instanceof Dog); //true Dog d1=(Dog) a; System.out.println(d1.furname); // yellow

  

原文地址:https://www.cnblogs.com/wujixing/p/5328404.html