品易云推流 关闭
文章详情页
文章 > java基础 > java向上转型发生的时机

java向上转型发生的时机

java向上转型

头像

小妮浅浅

2021-08-05 11:28:373823浏览 · 0收藏 · 0评论

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向上转型发生的时机,希望对大家有所帮助。更多Java学习指路:Java基础

本教程操作环境:windows7系统、java10版,DELL G3电脑。

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图