Master Core Java Step-by-Step!
Subscribe to Ram N Java for clear explanations, practical code examples, and essential interview insights!
Subscribe Now on YouTubeHow 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:
Dog constructor called
Critical Rules for super() in Java
- 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. - Automatic Insertion: If you do not explicitly add
super()orthis(), the Java compiler automatically inserts an invisiblesuper();call as the first line. - Cannot Mix super() and this(): A constructor can contain either a call to
super()or a call tothis(), but never both at the same time.
Watch More Java Inheritance Tutorials:
- 👉 Java super Keyword: Invoking Superclass Default Constructor with Compiler Insight | Java Tutorial
- 👉 Java super Keyword: Invoking Superclass Constructor with Parameters (Person Example) | Java Tutorial
- 👉 Java Inheritance IS-A Relationship | What is IS-A Relationship in Java Inheritance? | Java Tutorial
No comments:
Post a Comment