【问题标题】:How do I call an overridden parent class method from a child class?如何从子类调用重写的父类方法?
【发布时间】:2011-03-07 04:37:02
【问题描述】:

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

【问题讨论】:

标签: java inheritance


【解决方案1】:

调用超级

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;
   }
}

【讨论】:

  • A 类中的 foo() 方法不应该是静态的,以便您可以这样称呼它: super.foo() ?
  • @Eng 不!静态意味着非常不同的东西。
【解决方案2】:

这就是super 的用途。如果你重写方法method,那么你可以这样实现它:

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

【讨论】:

    【解决方案3】:

    一般可以使用关键字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();    
        }
    
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-23
      • 2020-08-09
      • 2019-05-18
      • 2017-07-07
      • 2020-04-26
      • 1970-01-01
      • 2017-11-09
      相关资源
      最近更新 更多