Skip to content
Advertisement

Behavior of costructors in sub classes in Java

let’s say I have the following code:

class A {
  Greating g = new Greating();
  public A(){system.out.print("Creating class A");}
}

class B extends A{
  public B(){system.out.print("Creating class B");}
}

class Greating{
  public Greating(){system.out.print("Hi");}
}

What are the outputs when I try to execute

public static void main(String[] args) {
  new B();
}

I thought it would first call the constructor of B and the constructor of B will call the constructor of A but the I don’t know which between “creating A” or “Hi” message will be shown first. The first thing invoked on a class should be its constructor but when I executed the program I noticed “Hi” was shown after “Creating A”. Why?

Advertisement

Answer

Output will be something like bellow:

Hi
Creating class A
Creating class B

Because at first constructor Greating() will be called to initialize property g of A then executed constructor A() and then executed constructor B()

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement