Course contentsShow
← Java
Lesson 408 of 2,87010. Inheritance FundamentalsFree lesson

Calling Specific Superclass Constructors with super(args)

Learn how to pass arguments to a specific superclass constructor using super(param1, param2, ...).

Calling Specific Superclass Constructors with super(args)

What you'll learn: How to explicitly choose which superclass constructor to invoke by passing arguments to super().


The Core Idea

In the previous lesson, you learned that super() calls the superclass's no-argument constructor by default. But what if your superclass has multiple constructors with different parameters? You can call a specific superclass constructor by passing the appropriate arguments to super(), just like you pass arguments to this() for constructor chaining within the same class.

The syntax is straightforward: super(param1, param2, ...) where the arguments match the parameter list of the superclass constructor you want to invoke.

Why This Matters

When a superclass requires initialization data (perhaps it has no default constructor, or you want to use a parameterized one), you must explicitly provide those values from the subclass constructor. This allows the superclass to properly initialize its inherited fields before the subclass adds its own initialization logic.

Example in Action

class Animal {
    protected String name;
    
    public Animal(String name) {
        this.name = name;
    }
}

class Dog extends Animal {
    private String breed;
    
    public Dog(String name, String breed) {
        super(name);  // Calls Animal(String name)
        this.breed = breed;
    }
}

Here, Dog's constructor accepts both a name and breed. It uses super(name) to pass the name up to Animal's parameterized constructor, ensuring the inherited name field gets initialized properly. Then it initializes its own breed field.

Remember: super(args) must be the first statement in the constructor, just like this().


Key Takeaway: Use super(arg1, arg2, ...) to call a specific parameterized constructor in your superclass, allowing flexible initialization of inherited state based on subclass needs.