您的位置:首页 > 编程语言 > Java开发

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

2016-03-28 11:36 435 查看
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); // errorSystem.out.println(a instanceof Animal); //true System.out.println(a instanceof Dog); //trueDog d1=(Dog) a;
System.out.println(d1.furname); // yellow


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: