首頁  >  文章  >  Java  >  java向上轉型發生的時機是什麼

java向上轉型發生的時機是什麼

PHPz
PHPz轉載
2023-05-20 08:43:12818瀏覽

1、直接賦值

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

2、方法傳參,把一個Cat的子類傳給一個Animal類型的父類,這裡也是能發生向上轉型的。

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

3、方法返回,func方法的返回類型是Animal,但返回的確是一個Cat類型,這裡也是發生了向上轉型。

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

以上是java向上轉型發生的時機是什麼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除