Review of Java_ Downcasting

First define a Fruit () class, and write big (), mid (), and small () methods in the class. Then define an Apple () class, rewrite the mid () method in this class, and write a subclass-specific sweet () method. Then write the test class Test (), in the Test class first perform upward transformation and then downward transformation. Go directly to the code.

public class Fruit {
    public void big(){
        System.out.println("大水果");
    }
    public void mid(){
        System.out.println("中型水果");
    }
    public void small(){
        System.out.println("小水果");
    }
}
public class Apple extends Fruit{
    public void mid(){
        System.out.println("中型水果哈哈哈");
    }
    public void sweet(){
        System.out.println("苹果很甜");
    }
}
public class Test {
    public static void main(String[] args) {
        Fruit apple01 = new Apple();//上转型
        //我们尝试调用两个Apple类的方法,发现调用不到sweet()方法(这个为子类特有的方法)
        apple01.mid();
        //apple01.sweet();
        //我们将编译类型转成Apple 父类的引用指向的是当前目标类型的对象
        Apple apple02 =(Apple) apple01;
        apple02.sweet();//成功调用到sweet()方法
    }
}

The result of the operation is as follows

medium fruit hahaha
apples are sweet

 Summarize

Syntax: subclass type reference name = (subclass type) parent class reference

Only the reference of the parent class can be forcibly transferred, but the object of the parent class cannot be forcibly transferred

It is required that the reference of the parent class points to an object of the current target type

After downcasting, all members in the subclass type can be called

Guess you like

Origin blog.csdn.net/ming2060/article/details/127796054
Recommended