thepieterdc thepieterdc - 1 year ago 63
Java Question

Java inheritance not behaving as expected

The following context is needed: The purpose of this way of coding is to avoid

statements and
; which is always a bad idea.

I have 3 classes with the following signatures:

abstract class A {}
class B extends A {}
class C extends A {}

Then I have another class with the following structure:

class MyClass {
private final A model;

public MyClass(A m) {
this.model = m;

public void doSomething() {
System.out.println(this.model instanceof C); //TRUE!!

private void execute(A m) {

private void execute(C m) {

And finally the contents of my main:

public static void main(String... args) {
C mod = new C();
MyClass myClass = new MyClass(mod);

Now the problem; the execute(C) method never gets executed, it's always the execute(A) method. How can I solve this? I cannot change the signature of the execute(A) method to execute(B) since that would give an error saying java "cannot resolve method execute(A)" at MyClass#doSomething.

Answer Source

Method overloads are resolved at compile time. At compile time, the type of m is A, so execute(A m) gets executed.

In addition, private methods are not overridable.

The solution is to use the Visitor pattern as suggested by @OliverCharlesworth.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download