多态的弊端以及向上转型和向下转型

public abstract class Animal {
    public abstract void eat();
}

  

public interface  CatchMouseAble {
    void catchMouse();
}

  

public interface SwimAble {
    void SwimAble();
}

  

public class Cat extends Animal implements CatchMouseAble{

    @Override
    public void eat() {
        System.out.println("猫吃鱼");
    }

    @Override
    public void catchMouse() {
        System.out.println("猫抓老鼠");
    }
}

  

public class Dog extends Animal implements SwimAble {
    @Override
    public void eat() {
        System.out.println("狗吃狗粮");
    }

    @Override
    public void SwimAble() {
        System.out.println("狗会游泳");
    }
}

  

/**
 * @program: spring
 * @description: ${description}
 * @author: Mr.zw
 * @create: 2021-05-10 22:27
 *
 *
 * 向上转型
 *     多态,父类引用指向子类对象,将子类的对象,转换成父类类型
 *     double d = 10; ->10->10.0
 *     Fu fu = new Zi(); ->对象(Zi)->对象(Fu)
 *  向下转型(强转)
 *     int i = (int)d;
 *     Zi zi = (Zi)fu;
 *
 *
 **/
public class AnimalTest {
    public static void main(String[] args) {
        //多态
        Animal a = new Dog();//父类引用指向子类对象 编译看左边,运行看右边
        a.eat();

        Animal a1 = new Cat();
        a1.eat();
        //Cat a1.catchMouse();报错 多态的弊端
        //多态情况下,使用父类的引用,不能直接访问子类特有的属性和行为
        ((Cat) a1).catchMouse();//解决方案:向下转型(强转)

        Animal a2 = new Cat();
        a2.eat();
        //ClassCastException:类型转换异常
        //class Cat cannot be cast to class Dog:类型Cat不能被转换成Dog
        //((Dog)a2).swim();//将猫转成了狗

        //判断,a2是否是cat类型
        if (a2 instanceof Cat) {
            ((Cat) a2).catchMouse();
        } else if (a2 instanceof Dog) {
            ((Dog) a2).SwimAble();
        }
    }
}

  

  

posted @ 2021-05-11 09:51  步江伍德  阅读(83)  评论(0)    收藏  举报