简体   繁体   English

在 java 中调用覆盖 function

[英]Calling an overriden function in java

I'm writing a piece of code in which I need to call an overridden method of a parent class. This is easy to do in C++:我正在编写一段代码,其中我需要调用父 class 的重写方法。这在 C++ 中很容易做到:

class A{
  public:
    void doPrint() {
        print();
    }
    
    void print(){
      cout << "This is A" << endl;
    }
};

class B: public A{
  public:
    void doPrint() {
        print();
    }
    
    void print(){
      A::doPrint();
    }
};

int main() {
  B b;
  b.doPrint();

  return 0;
}

However, I need to do this in java. My current java implementation trying to emulate this behavior from C++ is:但是,我需要在 java 中执行此操作。我当前的 java 实现试图从 C++ 模拟此行为:

class A {
    public void doPrint() {
        this.print();
    }
    
    public void print() {
        System.out.println("This is A");
    }
}

class B extends A {
    @Override
    public void doPrint() {
        this.print();
    }
    
    @Override
    public void print() {
        super.doPrint(); 
    }
    
}

public class main {
    public static void main(String[] args) {
        B b = new B();
        b.doPrint();
    }
}

However, when I do this I get a stackoverflow error caused by an infinite loop of doPrint and print:但是,当我这样做时,我得到了由 doPrint 和打印的无限循环引起的 stackoverflow 错误:

Exception in thread "main" java.lang.StackOverflowError
    at A.doPrint(A.java:4)
    at B.print(B.java:12)
    at A.doPrint(A.java:4)
    at B.print(B.java:12)
    at A.doPrint(A.java:4)
    at B.print(B.java:12)
    at A.doPrint(A.java:4)
    at B.print(B.java:12)

Is there a way to accomplish what I'm trying to do in Java?有没有办法完成我在 Java 中尝试做的事情? I'm having trouble seeing where my logic is going wrong.我很难看出我的逻辑哪里出了问题。

For instances of B, A's doPrint() which calls this.print() invokes the instance's implementation of print() , ie B's print() .对于 B 的实例,调用 this.print() 的 A 的doPrint() this.print()调用实例的print()实现,即 B 的print()

this.print() does not mean "the implementation of print() declared in this class". this.print()并不意味着“在此类中声明的print()的实现”。

this.print() is the same as just print() - qualifying it with this. this.print()print()相同 - 用this. is both implied and redundant.既隐含又多余。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM