Home >Java >javaTutorial >When does java upward transformation occur?

When does java upward transformation occur?

PHPz
PHPzforward
2023-05-20 08:43:12880browse

1. Direct assignment

public static void main(String[] args) {
        //父类引用 引用了 子类引用所引用的对象
        Animal animal = new Cat();;//向上转型
}

2. Method passing parameters, pass a Cat subclass to a parent class of Animal type, this can also be done here Upward transformation occurs.

public class Test extends TestDemo {
 
    public static void func(Animal animal) {
        
    }
    public static void main(String[] args) {
        //父类引用 引用了 子类引用所引用的对象
        Cat cat = new Cat();
        func(cat);
    }
}

3. Method return, the return type of the func method is Animal, but the return is indeed a Cat type, and upward transformation also occurs here.

public class Test extends TestDemo {
    public static Animal func() {
        Cat cat = new Cat();
        return cat;
    }
    public static void main(String[] args) {
        Animal animal = func();
    }
}

The above is the detailed content of When does java upward transformation occur?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete