thepieterdc thepieterdc - 7 months ago 11
Java Question

Java inheritance not behaving as expected

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

if
-
else
statements and
instanceof
; 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!!
execute(this.model);
}

private void execute(A m) {
System.out.println("noo");
}

private void execute(C m) {
System.out.println("yay");
}
}


And finally the contents of my main:

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


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.

EJP EJP
Answer

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.

Comments