如果调用了抽象方法,则由什么决定调用哪个实现方法?

tom*_*tom 1 java

abstract class A {

  // Here is an event listener that is called when an event occurs.
  // However, this event I don't want to process here but in class C.
  ...
    foo(processMe);
  ...

  // So using this abstract method I'm trying to delegate it to class C.
  public abstract void foo(String processMe);

}

class C extends A {

  // This is the method in which I'd like to handle the event,
  @Override
  public void foo(String processMe) { ... processing processMe ... }

  // ...but I have another class, class B that "steals the implementation".

}

// B extends A because there are many things B uses and implements from A.
class B extends A {

  // This method is completely unnecessary, it just has to be here as
  // abstract methods must be implemented in all extending subclasses.
  @Override
  public void foo(String processMe) { /* NOOP */ }

}
Run Code Online (Sandbox Code Playgroud)

其结果是,每一个事件发生时A,该方法foo()B被调用,而不是一个类C

我期待foo()B和中都可以调用它C。为什么会发生这种情况?对于我的问题,有什么更好的设计模式?


更新:

我无法显示更多代码,因为许多异步流程非常复杂。

B以及C在不同线程中运行的Runnable扩展A为使用其受保护的静态实用程序方法。A当另一个系统发送我要处理的数据时,将调用此事件侦听器C

更新2:

我发现了一个错误,该错误可以回答并使问题无关紧要,抱歉。在抽象类中,我使用单例实例创建事件处理程序。B首先创建用于类的线程,然后当它首次调用此构造函数时,它将抽象方法绑定到其自己的实现,该实现以后不会更改。

Jud*_*han 5

A a1 = new C(); 
a1.foo(); // execute foo() in C class

A a2 = new B(); 
a2.foo(); // execute foo() in B class
Run Code Online (Sandbox Code Playgroud)