这篇文章主要讲解了“java向上转型发生的时机是什么”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“java向上转型发生的时机是什么”吧!
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向上转型发生的时机是什么这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是天达云,小编将为大家推送更多相关知识点的文章,欢迎关注!