Sobes.tech
Junior

How to access overridden methods of a parent class in Java?

sobes.tech AI

Answer from AI

Use the keyword super.

super refers to an instance of the parent class and allows calling the parent's methods, even if they are overridden in the child.

Example:

// Parent class
class Parent {
    void display() {
        System.out.println("Parent class method");
    }
}

// Child class
class Child extends Parent {
    @Override
    void display() {
        // Call the overridden parent method
        super.display();
        System.out.println("Child class method");
    }
}

// Usage
class Main {
    public static void main(String[] args) {
        Child child = new Child();
        child.display();
    }
}

In this example, when child.display() is called, the display() method of the Child class executes. Inside this method, super.display() calls the display() method of the parent class Parent.