The super Keyword in Java


The super keyword refers to superclass (parent) objects and can be used to call superclass methods, access superclass constructors, and initialize superclass fields.

Source Code

class Animal {
    String color;

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

class Dog extends Animal {
    Dog() {
        super("brown"); // Call the constructor of the superclass (Animal)
        System.out.println("A dog's color: " + color);
    }
}

public class TestSuper {
    public static void main(String[] args) {
        new Dog();
    }
}

Use super to make superclass method calls, especially when overriding methods in a subclass, to access functionality defined in the superclass.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments