Hi all,
I recently fumbled into a problem with an API and an implementation where the following type of code appeared:
The API is an abstract class:
public abstract class A {
public A sum(A a) {
System.out.println("A.sum(A) called");
return null;
}
}
The implementation is a simple class:
public class B extends A {
public B sum(B b) {
System.out.println("B.sum(B) called");
return null;
}
}
When it comes to using it I write:
public class Main {
public static void main(String args[]) {
B b = new B();
A basa = new B();
b.sum(b);
basa.sum(b);
basa.sum(basa);
}
}
Which results in:
% java Main
B.sum(B) called
A.sum(A) called
A.sum(A) called
I understand that B's sum does not override A's sum as its signature is different, but I'd like to provide an efficient implementation of sum for objects of effective type B. I think such design is quite classical and would like to now how I should design my API and implementation so that it is efficient.
Of course, I could provide sum(A a) in class be and check if b is an instanceOf B before calling either sum(B) or super, but I thought that instanceOf was to be avoided for efficiency reasons (if it is inefficient, it may be even less efficient as my "abstract" implementation.