Upward type conversion VS downward type conversion

The rules when a subclass is converted to a parent class:

  • Pointing a reference of a parent class to an object of a subclass is called upcasting ( upcasting), which automatically performs type conversion. At this time, the method invoked by the parent class reference is the method of the subclass covering or inheriting the parent class, not the method of the parent class. At this time, it is not possible to call the unique method of the subclass through the parent class reference variable;
  • If the parent class wants to call the special method of the subclass, it has to assign a parent class reference pointing to the subclass object to a subclass reference, which is called downcasting. At this time, a coercive type conversion must be performed.
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("看家");
    }
}

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_45783660/article/details/114103307