每次在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