问题
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?
回答1:
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).
This is possible because the child class has a IS A relationship with its parent class since child inherits from parent.
回答2:
but how can Temp2() works as constructor for Temp1?
It doesn't. It is other way around. It is Temp1 t1
which behaves as reference which can hold any kind of object form Tempt1
family, and since Temp2 extends Temp1
it is considered as type of Type1
.
This is perfectly safe because Type2
inherits all members of Type1
so there is no risk that some method or field invoked on t1
reference will try to execute/use some undefined method/variable.
Also thanks to polymorphism (or to be more precise late-binding - searching and executing code of method at runtime based on instance type, not reference type) method of Type2
will be invoked instead of Type1
. This allows us to have abstract classes and interfaces.
回答3:
T1 do act as reference variable for Temp1
No, actually t1 variable is type of Temp1 which act as reference variable for Temp2.
but how can Temp2() works as constructor for Temp1
Inheritance is object oriented feature by which child class inherit all the property of parent class, in this case temp2 is child class which inheriting all the methods from its superclass temp1. Therefore temp2 is a type of temp1 family and therefore Temp2 constructor can refer by the Temp1 reference variable(t1).
You Must Read: https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html
来源:https://stackoverflow.com/questions/31327896/awkwardness-in-creating-object