Rahul Changaram Kandiyil
Rahul Changaram Kandiyil

Reputation: 1537

Can explain how the output is coming like this?

public class A {
  public A(){
    System.out.println("A created");        
  }
  public static void main(String[] args) {
    new B();
  }
}

class B extends A{
    public B(){
        System.out.println("B created");
    }       
}

the output of the above program will be

A created

B created

I can't understand how the constructor A() is invoked.There is no super called in B(). But still A() is invoked.

Upvotes: 0

Views: 106

Answers (2)

Thanakron Tandavas
Thanakron Tandavas

Reputation: 5683

When class B extends class A, it will call constructor A( ) by default.

That's the reason why the program prints A created before B created.

Upvotes: 7

MrLore
MrLore

Reputation: 3780

In child classes, super() is automatically called implicitly to ensure the object is properly constructed.

Upvotes: 2

Related Questions