为什么我们在Java中使用接口引用类型? [英] Why do we use Interface reference types in Java?
问题描述
我即将参加我的第一个面向对象编程课程的期末考试,我仍然不了解多态性的概念。
I'm about to take the final exam in my very first object-oriented programming class and I still don't understand something about the concept of polymorphism.
假设我有一个抽象类Vehicle,这个类有一个名为Aircraft的子类。我的问题是,这两个代码有什么不同?
Let's say I have an abstract class "Vehicle" and this class has one subclass named "Aircraft". My question is, what is the different between these two codes ?
Aircraft Jetplane = new Aircraft();
和
Vehicle Jetplane = new Aircraft();
推荐答案
在第二个,然后Jetplane可能是其他任何东西继承自车辆,而不仅仅是飞机。例如,你可以有类似的东西
In the second, then Jetplane could be anything else that inherits from Vehicle, not just an Aircraft. For example, you could have something like
Vehicle veh = null;
if (someCondition)
veh = new Aircraft();
else
veh = new Boat();
在第一个样本中无法完成,因为船不是飞机。
That can't be done in the first sample, because a Boat is not an Aircraft.
这篇关于为什么我们在Java中使用接口引用类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!