I have
interface FooI
class FooA implements FooI
class FooB implements FooI
class FooC implements FooI
I wrote a class "Handler" that has the following methods
static double handle(FooA f)
static double handle(FooB f)
static double handle(FooI f)
and I have a function like the following:
void caller(FooI f)
{
Handler.handle(f);
}
with f just being known as a class implementing FooI. However f is an instance of FooA
Instead of calling the method for FooA, the method for FooI is called.
When I use f.getClass().getName() I get the correct class name (FooA).
I am confused because I expected the best-suited method to get called, namely the one for FooA.
I wanted to use the FooI method as a fallback to handle classes that could be implemented later, and I also want to handle f without having one big function where I am doing instanceof checks for all currently known classes implementing my interface.
What would be a good approach to do this?
Overload resolution is done at compile time rather than execution time in Java. The signature was picked based on the compile-time type of your variable. Only overrides are determined at execution time.
A common solution for this in languages like Java is to use double dispatch and the visitor pattern.
Personally I'm not a huge fan of this. I prefer to try to design my way around it. That's not always possible, of course, but it's worth at least attempting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With