-2

I have a class A with a subclass B. The class A has a method foo() that calls C.test(this). In class C, there are two methods: test(A a) and test(B b). Whenever A.foo() is called, the method test(A a) is used. That seems normal to me. However, whenever B.foo() is called, the method test(A a) is also used, instead of test(B b) (which is what I want). This surprises me.

Why does this happen? How can I change my code structure such that I obtain the behaviour that I want?

Jeroen
  • 544
  • 3
  • 27

1 Answers1

0

I'm going to go off of an assumption that you're not overriding A#foo in B. So when A#foo is called, this refers to A since the method runs in A. To fix this, you can override the method in B by creating B#foo with the same implementation as its parent. this will then refer to B instead of A, and the correct method in C will be called.

Jacob G.
  • 28,856
  • 5
  • 62
  • 116