Java 类多态的向上转型
假定Base b = new Derived(); 调用执行b.methodOne()后,输出结果是什么?
1 public class Base 2 { 3 public void methodOne() 4 { 5 System.out.print("A"); 6 methodTwo(); 7 } 8 9 public void methodTwo() 10 { 11 System.out.print("B"); 12 } 13 } 14 15 public class Derived extends Base 16 { 17 public void methodOne() 18 { 19 super.methodOne(); 20 System.out.print("C"); 21 } 22 23 public void methodTwo() 24 { 25 super.methodTwo(); 26 System.out.print("D"); 27 } 28 }
语法格式:父类类型 对象名 = new 子类类型()
Animal animal = new Cat ();
Animal 是父类类型,但可以引用 Cat这个子类类型,因为是从小范围到大范围的转换。

1 class Aminal { 2 public void display() { 3 System.out.println("Animal"); 4 } 5 } 6 class Cat extends Aminal { 7 public void display() { 8 System.out.println("Cat"); 9 } 10 } 11 class Dog extends Aminal { 12 13 } 14 15 public class Main{ 16 public static void main(String[] args) { 17 Aminal aminal1 = new Aminal(); 18 Aminal aminal2 = new Cat(); 19 Aminal aminal3 = new Dog(); 20 21 aminal1.display(); 22 aminal2.display(); 23 aminal3.display(); 24 } 25 }
animal2中,Cat类 重写了 display方法,所以在实现时,打印的是Cat类中实现的内容。
animal3中,Dog类 没有重写 display方法,所以打印的还是父类中的内容。
由此我们可以得出:向上转型实现时
先看子类有没有
若是子类找不到
再看父类有没有
二者都无则报错!
3、向上转型的优缺点
优点:让代码实现更简单灵活
缺点:不能调用到子类特有的方法
class Animal { public void display() { System.out.println("Animal"); } } class Dog extends Animal { public void display() { System.out.println("dog"); } public void eat() { System.out.println("吃骨头"); } } public class Main { public static void main(String[] args) { Animal animal = new Dog(); animal.display(); animal.eat(); //会报错 } }
所以,向上转型无法调用子类特有的方法!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理