Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java method override/interface problem

Tags:

java

interface

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?

like image 797
Kage Avatar asked Dec 18 '25 02:12

Kage


1 Answers

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.

like image 134
Jon Skeet Avatar answered Dec 20 '25 18:12

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!