ADITYA DAS
ADITYA DAS

Reputation: 361

How to invoke overriden method of super class from static method of child class in java

Overridden methods of super class can be accessed from a child class using the keyword super but the child class method that is invoking the super class method must be non-static. How can I invoke super class overridden from a static method of child class.

class TakeMe{
    
    void display(){
        System.out.println("In super");
    }

}

public class Inher extends TakeMe{

    void display(){
        System.out.println("In child");
    }
    public static void main(String[] args) {
        Inher obj = new Inher();
        super.display();     //Error here
    }
}

This shows error Cannot use super in a static contextJava(536871112)

obj.super.display() doesn't work

Upvotes: -1

Views: 72

Answers (2)

ryckutis
ryckutis

Reputation: 119

Usage of super() inside the display() method is incorrect. Try this instead:

class TakeMe {
    void display() {
        System.out.println("In super");
    }
}

public class Inher extends TakeMe {
    void display() {
        super.display(); // <- here
        System.out.println("In child");
    }
    
    public static void main(String[] args) {
        Inher obj = new Inher();
        obj.display();     
    }
}

Upvotes: 1

shazin
shazin

Reputation: 21893

What you need is following;

class TakeMe{
    
    void display(){
        System.out.println("In super");
    }

}

public class Inher extends TakeMe{

    void display(){
        super();
        System.out.println("In child");
    }
    public static void main(String[] args) {
        Inher obj = new Inher();
        obj.display();     
    }
}

Upvotes: 0

Related Questions