java之对象转型

对象转型(casting)this

一、一个基类的引用类型变量能够“指向”其子类的对象。spa

二、一个基类的引用不能够访问其子类对象新增长的成员(属性和方法)。code

三、能够使用 引用变量 instanceof 类名 来判断该引用型变量所“指向”的对象是否属于该类或该类的子类。对象

四、子类的对象能够当作基类的对象来使用称做向上转型(upcasting),反之成为向下转型(downcasting)。blog

 

 
 
public class TestCasting{
    public static void main(String args[]){
        Animal a = new Animal("a");
        Cat c = new Cat("c","cEyesColor");
        Dog d = new Dog("d","dForlorColor");
        
        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 Dog);        //false
        
        a = new Dog("d2","d2ForlorColor");        //父类引用指向子类对象,向上转型
        System.out.println(a.name);                //能够访问
        //System.out.println(a.folorColor);   //!error   不能够访问超出Animal自身的任何属性
        System.out.println(a instanceof Animal);    //是一只动物
        System.out.println(a instanceof Dog);        //是一只狗,可是不能访问狗里面的属性
        
        Dog d2 = (Dog)a;    //强制转换
        System.out.println(d2.folorColor);    //将a强制转换以后,就能够访问狗里面的属性了
    }
}
class Animal{
    public String name;
    public Animal(String name){
        this.name = name;
    }
}
class Dog extends Animal{
    public String folorColor;
    public Dog(String name,String folorColor){
        super(name);
        this.folorColor = folorColor;
    }
}
class Cat extends Animal{
    public String eyesColor;
    public Cat(String name,String eyesColor){
        super(name);
        this.eyesColor = eyesColor;
    }
}
 
 

 

 

运行结果:ast

相关文章
相关标签/搜索