-5
abstract class A {
    abstract void method();
}

class B extends A {
    B() {
    }

    void method() {
    }
}

class C extends B {
    C() {
    }
}

When I instantiate class C in main, it automatically calls the constructor for B (parent class). Is that normal or am I doing something wrong?

Jeffmagma
  • 452
  • 2
  • 8
  • 20
pavinan
  • 1,275
  • 1
  • 12
  • 23

4 Answers4

5

There is nothing wrong, there is implicit call to super constructor.

You haven't written any constructor for class C so default constructor will be provided by compiler which will be.

C(){
  super(); 
 }

If default constructor is provided, then there is a call to super(). In your case, C extends B so constructor of B gets called.

If you do not a class with any other class, then also by default it extends Object class. So Object class constructor will get called.

Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
2

If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body implicitly begins with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments.

http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.8.7

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
1

When you instantiate a C there will be constructor calls for C, B, A, and Object. A C has to be able to behave as any direct or indirect superclass, and has the fields for all of them. The job of a class X constructor is to make the object being initialized capable of working as an X.

If there is no declared constructor, the compiler creates a parameterless constructor, so every class does have at least one constructor. If a constructor that is not the Object constructor does not start with a "this" or "super" constructor call, the compiler treats it as starting with "super();", a call to a parameterless constructor for the immediate superclass.

Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75
0

First line of each constructor in java calls super constructor, thats how java works. You should read about it.

Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
Lokesh
  • 7,810
  • 6
  • 48
  • 78