Is object created every time a constructor is called in java? Here Apple class inherits from Fruit.Apple object is created.As it inherits from Fruits,Fruit's constructor is called(constructor chaining).That means Fruit's object has been initialized.
But the output suggests that only 1 object is created,Apple object.Both have same hashcode.
Can someone please explain?.I expected 2 objects to be there.First Fruit object should have been initialized,then apple object.
// A Java program to demonstrate that both super class // and subclass constructors refer to same object
// 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