Tuesday, 2 February 2016

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

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

Real-World Example: Parameterized super() with a Person Class

In object-oriented programming, real-world entities naturally share common attributes. For instance, both an Employee and a Student are essentially a Person with common fields like an ID, a name, or an address.

Instead of rewriting initialization logic in every subclass, you can pass these common attributes directly to the parent class constructor using the parameterized call: super(id, name);.

Why Delegate Initialization to the Superclass?

Using super() with parameters offers key advantages in clean software design:

  • DRY Principle (Don't Repeat Yourself): Common member initialization stays localized inside the parent class, avoiding duplicate assignment statements.
  • Proper State Encapsulation: Even if parent fields are private, subclasses can easily set up those values through the parent constructor.
  • Consistent Object Construction: Ensures the foundational fields of the parent class are fully validated and assigned before subclass-specific members are set.

Complete Code Example: Person and Employee Hierarchy

class Person {
  int id;
  String name;

  Person(int id, String name) {
    this.id = id;
    this.name = name;
  }
}

class Employee extends Person {
  float salary;

  Employee(int id, String name, float salary) {
    super(id, name); // Forwarding id and name to the Person constructor
    this.salary = salary;
  }

  void display() {
    System.out.println(id + " | " + name + " | $" + salary);
  }
}

public class Test {
  public static void main(String[] args) {
    Employee emp = new Employee(101, "Alex", 75000f);
    emp.display();
  }
}

Output:

101 | Alex | $75000.0

Essential Rules to Remember

  1. The call to super(...) must always be the first statement inside the constructor body.
  2. The arguments passed to super(...) must match the type and sequence of the parent class constructor signature.
  3. If a parent class only defines a parameterized constructor, any subclass constructor must explicitly invoke super(...) with appropriate parameters.

Watch More Java Inheritance Tutorials:

No comments:

Post a Comment

Tutorials