If a subclass constructor does not explicitly call a superclass constructor


What happens if a subclass constructor does not explicitly call a superclass constructor?

If a subclass constructor does not explicitly call a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the superclass does not have a no-argument constructor, you will get a compile-time error. In such a case, you must explicitly call a superclass constructor yourself.

The subclass will still inherit the instance variables and methods from the superclass

If a subclass constructor does not explicitly call a superclass constructor, the Java virtual machine will insert a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. In this example, there is no explicit call to the superclass constructor, so the default no-argument constructor of Object is called first, followed by the constructor of A, and then finally B:

However, the subclass will not have access to the superclass’s constructor code

If a subclass constructor does not explicitly call a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. However, the subclass will not have access to the superclass’s constructor code. In this case, the compiler will issue an error if the superclass does not have a no-argument constructor.

This can lead to unexpected behavior in the subclass


If a subclass constructor does not explicitly call a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. In this situation, you must explicitly call a superclass constructor.

For example, consider the following classes:

class A {
public A() {
// ….
}

// …
}

class B extends A {
public B() {

  // The compiler inserts a call to the no-argument 
  // constructor of super class A. 

  // ...      

}

// …
}


Leave a Reply

Your email address will not be published.