Java 对象转型

对象转型

  • 规则一:一个基类的引用类型可以指向其子类对象。
  • 规则二:一个基类的引用不可以访问其子类对象新增加的成员(属性和方法)。
  • 规则三:可以使用“变量instanceof类名”来判断该引用是否指向该类或该类的子类。
  • 规则四:子类的对象可以当作基类的对象来使用称作向上转型,反之称作向下转型。
class Animal
{
    public String name;
    Animal(String name)
    {
        this.name = name;
    }
}
class Cat extends Animal
{
    public String eyescolor;
    Cat(String n,String c)
    {
        super(n);
        eyescolor = c;
    }
}
class Dod extends Animal
{
    public String furcolor;
    Dog(String n,String c)
    {
        super(n);
        furcolor = c;
    }
}
puclic class Test
{
    public static void main(String args[])
    {
        Animal a = new Animal("name");
        Cat c = new Cat("catname","blue");
        Dog d = new Dog("dogname","black");
        
        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 Cat);//false,违反规则三
        
        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 instance Dog);//true,规则三
        //注意instanceof实际上看的是这个引用指向的对象,而不是这个引用的类型
        Dog d1 = (Dog)a;//强制转换,向下转型
        System.out.println(di.furcolor);//yellow
    }
}
原文地址:https://www.cnblogs.com/031602523liu/p/8654185.html