java 如何从子类调用重写的父类方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5215873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 10:00:45  来源:igfitidea点击:

How do I call an overridden parent class method from a child class?

javainheritance

提问by Paul

If I have a subclass that has methods I've overridden from the parent class, and under very specific situations I want to use the original methods, how do I call those methods?

如果我的子类具有从父类重写的方法,并且在非常特殊的情况下我想使用原始方法,我该如何调用这些方法?

采纳答案by corsiKa

call super

呼叫超级

class A {
   int foo () { return 2; }
}

class B extends A {

   boolean someCondition;

   public B(boolean b) { someCondition = b; }

   int foo () { 
       if(someCondition) return super.foo();
       return 3;
   }
}

回答by Ted Hopp

That's what superis for. If you override method method, then you might implement it like this:

super就是为了。如果您覆盖 method method,那么您可能会像这样实现它:

protected void method() {
    if (special_conditions()) {
        super.method();
    } else {
        // do your thing
    }
}

回答by booooh

You can generally use the keyword superto access the parent class's function. for example:

通常可以使用关键字super来访问父类的函数。例如:

public class Subclass extends Superclass {

    public void printMethod() { //overrides printMethod in Superclass
        super.printMethod();
        System.out.println("Printed in Subclass");
    }
    public static void main(String[] args) {

    Subclass s = new Subclass();
    s.printMethod();    
    }

}

Taken from http://download.oracle.com/javase/tutorial/java/IandI/super.html

取自http://download.oracle.com/javase/tutorial/java/IandI/super.html