In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
这篇文章主要介绍"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(); }}
实例扩展:
package multistate;public class Human { public void sleep() { System.out.println("Human sleep.."); } public static void main(String[] args) { Human h = new Male();// 向上转型 h.sleep(); Male m = new Male();// 干嘛要向上转型 m.sleep(); // h.speak();此方法不能编译,报错说Human类没有此方法 }}class Male extends Human { @Override public void sleep() { System.out.println("Male sleep.."); } public void speak() { System.out.println("I am Male"); }}class Female extends Human { @Override public void sleep() { System.out.println("Female sleep.."); } public void speak() { System.out.println("I am Female"); }}关于"Java多态向上转型的方法"的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注行业资讯频道,小编每天都会为大家更新不同的知识点。
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.