Friday, 29 January 2016

Java Tutorial : Java super keyword (Invoke super class default constructor)

Master Core Java Step-by-Step!

Subscribe to Ram N Java for clear explanations, practical code examples, and essential interview insights!

Subscribe Now on YouTube

How to Invoke a Superclass Constructor with super()

In Java inheritance, when an instance of a subclass is created, the constructor of the parent class (superclass) runs before the subclass constructor logic executes. This process is called constructor chaining.

You can explicitly invoke the default (no-argument) constructor of the superclass using the special syntax: super(); inside the child class constructor.

Why Do We Use super() in Constructors?

When modeling real-world objects using inheritance, parent classes usually handle foundational setup and member initialization. Calling super() ensures that:

  • Proper Object Initialization: The parent object state is established before the child class initializes its own fields.
  • Explicit Code Clarity: Writing super(); explicitly tells other developers that the parent constructor is being intentionally executed.
  • Order of Execution: The superclass constructor always finishes executing before the remainder of the subclass constructor runs.

Step-by-Step Code Example

class Animal {
  Animal() {
    System.out.println("Animal constructor called");
  }
}

class Dog extends Animal {
  Dog() {
    super(); // Explicitly calls the Animal default constructor
    System.out.println("Dog constructor called");
  }
}

public class Test {
  public static void main(String[] args) {
    Dog d = new Dog();
  }
}

Output:

Animal constructor called
Dog constructor called

Critical Rules for super() in Java

  1. Must be the First Statement: super() must always be the very first line of code inside the constructor body. Placing it anywhere else causes a compilation error.
  2. Automatic Insertion: If you do not explicitly add super() or this(), the Java compiler automatically inserts an invisible super(); call as the first line.
  3. Cannot Mix super() and this(): A constructor can contain either a call to super() or a call to this(), but never both at the same time.

Watch More Java Inheritance Tutorials:

No comments:

Post a Comment

Tutorials