java之对象转型

对象转型(casting)

1、一个基类的引用类型变量可以“指向”其子类的对象。

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

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

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

 


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;
    }
}

 

 

运行结果:

posted @ 2014-10-05 10:16  高杰才_Android  阅读(4611)  评论(0编辑  收藏  举报