CodeGym /Courses /JAVA 25 SELF /Using super: calling the base class constructor and metho...

Using super: calling the base class constructor and methods

JAVA 25 SELF
Level 17 , Lesson 2
Available

1. Using super to call base-class methods

When you create a subclass, sometimes you need to refer to fields or methods of the base class, especially if you have overridden or “shadowed” them in the subclass. For this, Java has a special keyword — super.

By analogy, super is like “Mom, help!” when in a subclass you want to explicitly refer to what is defined in the parent.

Imagine you have a class Animal with a method eat() that just prints "The animal eats". And in the class Cat you want the cat to first do something of its own (for example, meow), and then still perform the standard “animal eats”. That’s where super.eat() comes in handy.

When you override a method in a subclass but still want to call that method’s implementation from the base class inside it, use super.methodName().

Example: extending behaviour

class Animal {
    void eat() {
        System.out.println("The animal eats");
    }
}

class Cat extends Animal {
    @Override
    void eat() {
        System.out.println("The cat sniffs the food...");
        super.eat(); // call eat() from Animal
        System.out.println("The cat purrs contentedly");
    }
}

How does this work?

  • When eat() is called on an object of type Cat, the code from Cat.eat() runs first, i.e., the subclass’s own method.
  • Inside that method we explicitly call super.eat(), i.e., the implementation from the parent class Animal.
  • This lets you add additional behaviour without forgetting the “parent’s” logic.

Practice: using it in an app

Suppose our learning app has a base class Animal and subclasses Dog and Cat. We want feeding an animal to perform both common actions (for example, increasing satiety) and those specific to each animal.

class Animal {
    int satiety = 0;

    void eat() {
        satiety += 10;
        System.out.println("The animal eats. Satiety: " + satiety);
    }
}

class Dog extends Animal {
    @Override
    void eat() {
        System.out.println("The dog wags its tail before eating");
        super.eat();
    }
}

Now, if you call dog.eat(), you will see both messages, and satiety will increase correctly.

2. Using super to access base-class fields

If in a subclass you declare a field with the same name as in the parent class, it “shadows” the parent’s field. Sometimes you need to access the original field from the base class — that’s what super.fieldName is for.

Example: field shadowing

class Animal {
    String name = "Animal";
}

class Cat extends Animal {
    String name = "Cat";

    void printNames() {
        System.out.println("Name from Cat: " + name);
        System.out.println("Name from Animal: " + super.name);
    }
}

Calling new Cat().printNames(); will print:

Name from Cat: Cat
Name from Animal: Animal

In real practice, shadowing fields is not recommended unless absolutely necessary, but it’s worth knowing about this possibility.

3. Calling the base class constructor via super(...)

How are objects created in a hierarchy?

When you create an object of a subclass, the base class constructor runs first, and only then the subclass constructor. This is needed so that all fields are initialized correctly, since the subclass “inherits” part of its state from the parent.

Explicitly calling the base class constructor

If the base class has a no-arg constructor, it’s simple: Java will call it automatically before running the subclass constructor. But if the parent does not have a no-arg constructor, you must explicitly call the required constructor via super(...).

Example:

class Animal {
    String name;

    Animal(String name) {
        this.name = name;
        System.out.println("Animal created: " + name);
    }
}

class Cat extends Animal {
    Cat(String name) {
        super(name); // required! There is no no-arg Animal() constructor
        System.out.println("Cat created: " + name);
    }
}

Calling new Cat("Murka") will print:

Animal created: Murka
Cat created: Murka

Important: Calling the parent constructor via super(...) must be the first line of the subclass constructor. If you try to put anything before this call, the compiler will complain and remind you about it.

What if you don’t call it explicitly?
If the parent only has constructors with parameters and you do not call one explicitly via super(...), the compiler will issue an error: "constructor Animal in class Animal cannot be applied to given types".

4. Useful nuances

When to use super?

To extend, not replace, behaviour.
Sometimes you don’t want to completely replace a method’s behaviour but only extend it — for example, add something before or after the parent logic. In such cases use super.methodName() in the body of the overridden method.

To initialize inherited fields.
If the parent has fields that must be initialized (for example, an animal’s name), be sure to call the parent constructor with the required parameters via super(...).

To access shadowed fields/methods.
If for some reason you have shadowed a parent field or method and still need to access it, use super.fieldName or super.methodName().

Limitations and specifics of using super

  • Calling the parent constructor via super(...) can only be done in a constructor and only as the first line.
  • You cannot call the parent constructor outside of a subclass constructor.
  • If you don’t call super(...) explicitly, Java will try to call the parent’s no-arg constructor (if it exists).
  • The super keyword cannot be used in static methods — only in instance methods and constructors.
  • If a parent’s method or field is private, super won’t help: private members are not accessible.

5. Practice examples

Example 1. Extend a method using super

class Animal {
    void makeSound() {
        System.out.println("The animal makes a sound");
    }
}

class Dog extends Animal {
    @Override
    void makeSound() {
        super.makeSound(); // perform the standard action first
        System.out.println("The dog barks: Woof-woof!");
    }
}

Example 2. Calling the base class constructor

class Vehicle {
    String brand;

    Vehicle(String brand) {
        this.brand = brand;
        System.out.println("Vehicle: " + brand);
    }
}

class Car extends Vehicle {
    int year;

    Car(String brand, int year) {
        super(brand); // call the parent constructor
        this.year = year;
        System.out.println("Car " + brand + ", year: " + year);
    }
}
Car car = new Car("Toyota", 2023);
// Output:
// Vehicle: Toyota
// Car Toyota, year: 2023

Example 3. A classic mistake: forgot to call super(...)

class Animal {
    String name;

    Animal(String name) {
        this.name = name;
    }
}

class Cat extends Animal {
    Cat() {
        // super(); // Error! No Animal() constructor without parameters
        // You must explicitly call super(name)
        super("Unnamed cat");
    }
}

6. Common mistakes when working with super

Error No. 1: Calling super(...) not as the first line of the constructor.
Java strictly requires that the call to the parent constructor via super(...) be the first line of the subclass constructor. If you try to do something before that call (for example, print a message), the compiler will issue an error.

Error No. 2: No suitable constructor in the parent.
If the base class has no no-arg constructor and you did not call another constructor via super(...), the compiler cannot generate the default call and will report an error.

Error No. 3: Attempting to access the parent’s private members via super.
The super keyword does not grant magical access to private fields or methods of the parent. If something is declared private, it remains inaccessible to the subclass.

Error No. 4: Shadowing fields and methods without understanding.
If you declare in a subclass a field or method with the same name as in the parent and forget about it, unexpected results are possible. Always remember that in this case access to the parent member is only via super.

Error No. 5: Using super in a static method.
You cannot use super in static methods because they do not belong to a specific object.

1
Task
JAVA 25 SELF, level 17, lesson 2
Locked
Sounds of Nature: From General to Specific 🐺
Sounds of Nature: From General to Specific 🐺
1
Task
JAVA 25 SELF, level 17, lesson 2
Locked
Factory pipeline: Vehicle and Car Assembly 🏭
Factory pipeline: Vehicle and Car Assembly 🏭
1
Task
JAVA 25 SELF, level 17, lesson 2
Locked
Pet Lineage: Names at Different Levels 🐾
Pet Lineage: Names at Different Levels 🐾
1
Task
JAVA 25 SELF, level 17, lesson 2
Locked
University system: Student registration 👨‍🎓
University system: Student registration 👨‍🎓
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION