向上类型转换VS向下类型转换

子类转换成父类时的规则:

  • 将一个父类的引用指向一个子类的对象,称为向上转型(upcasting),自动进行类型转换。此时通过父类引用调用的方法是子类覆盖或继承父类的方法,不是父类的方法。 此时通过父类引用变量无法调用子类特有的方法;
  • 如果父类要调用子类的特有方法就得将一个指向子类对象的父类引用赋给一个子类的引用,称为向下转型,此时必须进行强制类型转换。
package class01;

public class demo {
    
    
    public static void main(String[] args) {
    
    
        show(new Cat()); // 以 Cat 对象调用 show 方法
        show(new Dog()); // 以 Dog 对象调用 show 方法
        Animal a = new Cat(); // 向上转型
        a.eat(); // 调用的是 Cat 的 eat
        Cat c = (Cat) a; // 向下转型
        c.work(); // 调用的是 Cat 的 work
    }
    public static void show(Animal a) {
    
    
        a.eat();
        // 类型判断
        if (a instanceof Cat) {
    
     // 猫做的事情
            Cat c = (Cat) a;
            c.work();
        } else if (a instanceof Dog) {
    
     // 狗做的事情
            Dog c = (Dog) a;
            c.work();
        }
    }
}
abstract class Animal {
    
    
    abstract void eat();
}
class Cat extends Animal {
    
    
    public void eat() {
    
    
        System.out.println("吃鱼");
    }
    public void work() {
    
    
        System.out.println("抓老鼠");
    }
}
class Dog extends Animal {
    
    
    public void eat() {
    
    
        System.out.println("吃骨头");
    }
    public void work() {
    
    
        System.out.println("看家");
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_45783660/article/details/114103307