《Java编程思想》读书笔记——向上转型与向下转型

xiaoxiao2021-03-01  23

向上转型即导出类能够转型为基类,让我们来看看下面的例子。

public class Animal { public void eat(){ System.out.println("Animal eat()"); } } public class Dog extends Animal { @Override public void eat(){ System.out.println("Dog eat"); } } public class Test { public static void main(String[] args) { //向上转型 Animal animal = new Dog(); animal.eat(); } } 输出结果: Dog eat

因为Dog类继承了Animal类,所以可以把Dog对象看成Animal对象,故能用Animal引用来接收一个Dog对象。这就是所谓的向上转型。 向上转型的概念很简单,但是为什么要叫这种转型为向上转型而不是向下转型呢?

该术语的使用有着历史原因,并且是以传统的类继承图的绘制为基础的:将根置于页面的顶端,然后逐渐向下。由导出类转型成基类,在继承图上是向上移动的,因此一般称为向上转型。

由于向上转型是从一个较专用类型向较通用类型转换,所以总是很安全的。也就是说,导出类是基类的一个超集。它可能比基类含有更多的方法,但它至少具备基类中所含的所有方法。在向上转型的过程中,类接口中唯一可能发生的事情是丢失方法,而不是获取它们。这就是为什么编译器在“未曾明确表示转型”或“未曾指定特殊标记”的情况下,仍然允许向上转型的原因。

既然有了向上转型,那么Java中是否存在向下转型呢?我们来看看下面例子:

public class Animal { public void eat(){ System.out.println("Animal eat()"); } } public class Dog extends Animal { @Override public void eat(){ System.out.println("Dog eat"); } } public class Test { public static void main(String[] args) { //向下转型 Animal animal = new Animal(); ((Dog)animal).eat(); } } 运行结果: Exception in thread "main" java.lang.ClassCastException: com.hello.test.Animal cannot be cast to com.hello.test.Dog at com.hello.test.Test.main(Test.java:7)

从上述例子来看,Java似乎并不支持向下转型,真是如此吗?其实不然,Java同样支持向下转型,只是向下转型是有条件的——只有引用子类对象的父类引用才能被向下转型为子类对象。也就是说,向下转型之前,必须先向上转型。

public class Animal { public void eat(){ System.out.println("Animal eat()"); } } public class Dog extends Animal { @Override public void eat(){ System.out.println("Dog eat"); } } public class Test { public static void main(String[] args) { //向上转型 Animal animal = new Dog(); //向下转型 ((Dog)animal).eat(); } } 运行结果: Dog eat
转载请注明原文地址: https://www.6miu.com/read-4150141.html

最新回复(0)