java中如何从子类的静态方法调用超类的重写方法

问题描述 投票:0回答:1

可以使用关键字

super
从子类访问超类的重写方法,但调用超类方法的子类方法必须是非静态的。如何调用从子类的静态方法重写的超类。

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();
        System.out.println(obj.a);
        super.display();     //Error here
    }
}

这显示错误

Cannot use super in a static contextJava(536871112)

obj.super.display()
不起作用

java inheritance static-methods super superclass
1个回答
0
投票

您需要的是以下内容;

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();     
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.