How to call the correct overloaded method? [duplicate]
Clash Royale CLAN TAG#URR8PPP
How to call the correct overloaded method? [duplicate]
This question already has an answer here:
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.
foo()
C.test(this)
test(A a)
test(B b)
A.foo()
test(A a)
B.foo()
test(A a)
test(B b)
Why does this happen? How can I change my code structure such that I obtain the behaviour that I want?
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
Have you tried overriding
foo()
in B
?– Khodabakhsh
Aug 12 at 19:25
foo()
B
1 Answer
1
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.
A#foo
B
A#foo
this
A
A
B
B#foo
this
B
A
C
Please post a real-code example of exactly what you mean, a Minimal, Complete, and Verifiable example.
– Hovercraft Full Of Eels
Aug 12 at 19:24