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 }
复制代码

 

 

一、什么是向上转型

1、概念

向上转型就是创建一个子类对象,将其当成父类对象来使用。

语法格式:父类类型  对象名  =  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(); //会报错
    }
}
复制代码

 

所以,向上转型无法调用子类特有的方法!

 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
posted @   "β.ί.ο.ς"  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示