Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If an abstract method is invoked, what decides which of its implementing methods gets called?

Tags:

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 */ }

}

And the result is that every time that event occurs in A, the method foo() of B gets called instead of the one in class C.

I was expecting that foo() would be called in both B and C. Why is this happening and what could be a better design pattern for my problem?


Update:

I couldn't show much more of the code as it's quite complex with many async processes.

B and C are Runnables running in different Threads extending A to use its protected static utility methods. There is this event listener in A that is called when another system sends data that I'd like to process in C.

Update 2:

I've found a bug that answers and makes the question irrelevant, sorry. In the abstract class I used a singleton instance to create the event handler. The thread for class B is created first, and when it first invokes this constructor it binds the abstract method to its own implementation which later doesn't change.

like image 582
tom Avatar asked Nov 23 '25 03:11

tom


2 Answers

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

A a2 = new B(); 
a2.foo(); // execute foo() in B class
like image 90
Jude Niroshan Avatar answered Nov 24 '25 20:11

Jude Niroshan


The concrete instance that is assigned to the reference decides that.

like image 23
muasif80 Avatar answered Nov 24 '25 20:11

muasif80



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!