您的位置:首页 > 其它

引用类型变量的转型

2016-07-06 16:27 281 查看
class Animal

{

    private String name;

    Animal(String name)

    {

        this.name = name;

    }

}

class Dog extends Animal

{

    private String furColor;

    Dog(String name,String furColor)

    {

        super(name);

        this.furColor = furColor;

    }

    void laugh(Animal a)

    {

        if(a instanceof Dog)

        {

            Dog d = (Dog)a;

            System.out.println("furColor is "+d.furColor+"'s dog " +"laughs");

        }

    }

}

class Cat extends Animal

{

    private String eyeColor;

    Cat(String name,String eyeColor)

    {

        super(name);

        this.eyeColor = eyeColor;

    }

    void laugh(Animal a)

    {

        if(a instanceof Cat)

        {

            Cat c = (Cat)a;

            System.out.println("eyeColor is "+c.eyeColor+"'s cat " +"laughs");

        }

    }

}

public class TestCasting

{

    public static void main(String[] args)

    {

        Animal a = new Animal("Animal");

        Dog d = new Dog("Dog","yellow");

        Cat c = new Cat("Cat","blue");

        //a.laugh();

        Dog d1 = new Dog("Dog1","black");

        d.laugh(d1);

        c.laugh(c);

    }

}

/*

总结:

1.对象转型可以提高程序的扩展性

2.父类引用可以指向子类对象,但是父类只能访问子类从父类继承来的东西

而不能访问子类所特有的

3.转型(casting)

upcasting和downcasting

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