尴尬在创造对象 [英] awkwardness in creating object
问题描述
Temp1 t1 = new Temp2();
这里Temp1是Temp2的超类。代码工作完全正常, t1 做为Temp1的参考变量,但是如何 Temp2()可以作为Temp1的构造函数?
Temp1 t1=new Temp2();
Here Temp1 is superclass of Temp2. The code works perfectly fine and t1 do acts as a reference variable for Temp1 but how can Temp2() works as constructor for Temp1?
推荐答案
这是的基础多态性:想象一下,你有几个继承自父类的子类。您希望通过在父类上定义的接口/方法使用所有这些子类,而不必担心每个子类中的实现细节(每个子类都可能执行不同的操作,但具有相同的整体语义)。
This is the basis for polymorphism: Imagine you have several child classes that inherit from you parent class. You want to use all these child classes through the interface / methods defined on your parent class, without worrying about the implementation details in each child class (each might do something different, but with the same overall semantics).
这是可能的,因为子类有 IS A 与父类继承的父类之间的关系。
This is possible because the child class has a IS A relationship with its parent class since child inherits from parent.
这篇关于尴尬在创造对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!