每次在java中調用構造函數時都創建對象嗎? 這裏的Apple類是從Fruit.Apple對象繼承而來的。當它繼承自Fruits時,Fruit的構造函數被調用(構造函數鏈)。這意味着Fruit的對象已經被初始化。每次在java中調用構造函數時是否創建對象?
但輸出表明只有1個對象被創建,Apple對象。兩者都具有相同的哈希碼。
有人可以解釋一下嗎?.I預計有2個對象在那裏。第一個Fruit對象應該已經被初始化,然後是Apple對象。
// Java程序來證明這兩個超類 //和子類的構造函數是指同一個對象
// super class
class Fruit
{
public Fruit()
{
System.out.println("Super class constructor");
System.out.println("Super class object hashcode :" +
this.hashCode());
System.out.println(this.getClass().getName());
}
}
// sub class
class Apple extends Fruit
{
public Apple()
{
System.out.println("Subclass constructor invoked");
System.out.println("Sub class object hashcode :" +
this.hashCode());
System.out.println(this.hashCode() + " " +
super.hashCode());
System.out.println(this.getClass().getName() + " " +
super.getClass().getName());
}
}
// driver class
public class Test
{
public static void main(String[] args)
{
Apple myApple = new Apple();
}
}
Output
Super class constructor
Super class object hashcode :366712642
Apple
Subclass constructor invoked
Sub class object hashcode :366712642
366712642 366712642
Apple Apple
[Java中的繼承 - 創建子類的對象也會調用超類的構造函數。爲什麼?](http://stackoverflow.com/questions/488727/inheritance-in-java-creating-an-object-of-the-subclass-invokes-also-the-constr) – DVarga