Tuesday, 2 February 2016

Java Tutorial : Java Super Keyword (Invoke super-class constructor with parameter)

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

Passing Arguments to Superclass Constructors

In Java inheritance, subclasses frequently need to pass specific data up to parent class constructors during object creation. While a default constructor takes no values, a parameterized superclass constructor allows you to set up essential parent fields immediately.

To pass arguments up to a parent constructor, Java provides the parameterized syntax: super(argument1, argument2, ...);.

Why Use super() with Parameters?

Calling parameterized constructors in the superclass provides several key advantages:

  • Code Reusability: Instead of duplicating initialization code in the child class, the parent constructor handles common setup logic.
  • Data Encapsulation: Private parent variables can be safely initialized via the superclass constructor without exposing direct access.
  • Explicit Control: It ensures that the parent object state is properly established with valid data right at the moment of instantiation.

Step-by-Step Code Example

class Animal {
  String name;

  // Parameterized parent constructor
  Animal(String name) {
    this.name = name;
    System.out.println("Animal constructor called for: " + name);
  }
}

class Dog extends Animal {
  String breed;

  Dog(String name, String breed) {
    super(name); // Passes the name argument to the parent constructor
    this.breed = breed;
    System.out.println("Dog breed: " + breed);
  }
}

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

Output:

Animal constructor called for: Buddy
Dog breed: Labrador

Key Rules to Follow

  1. Must Be the First Line: Just like the default super() call, super(...) with parameters must always be the very first statement inside the subclass constructor.
  2. Matching Arguments: The argument count, order, and data types passed into super(...) must exactly match a constructor signature in the superclass.
  3. No Multiple Invocations: You cannot call super(...) more than once within the same constructor.

Watch More Java Inheritance Tutorials:

No comments:

Post a Comment

Tutorials