Java method overload using interface

I am sure that this is elementary, but I'm at a standstill. The example is extremely simplified, but boils down to the following. I have some overloaded methods in a class like:

public void build(MyImplOneOfAnInterface item);
public void build(MyImplTwoOfAnInterface item);

Then I have another method that does the following:

public void buildIt(MyInterface item) {
     build(item);
}

When I try to compile, I get the following error:

can't find character

This is because the JVM cannot determine the implementation of the interface at compile time, so that it knows what overloaded method to call.

How can this be solved at runtime? It seems that the JVM should be able to understand this.

PS: I do not want to define a method that takes an interface as an argument, and then executes a bunch of if / else statements using instanceof statements.

+5
4

. MyInterface.build, , . :.

interface MyInterface {
    void build(Thingy t);
}

class MyImplOneOfAnInterface implements MyInterface {
    void build(Thingy t) { t.build(this); }
}

...

void buildIt(MyInterface item) {
    item.build(this);
}
+7

build() ., build(item) item.build().

, item.build(builder) builder.build(item)

+3

.

MyImplOne... MyImplTwo - . build (item),

public void build(MyInterface item):

else, , , , MyImplOne, MyImplTwo.

public void print(Vector vector);

,

print(new Object());
+1
source

It is passed in void buildIt(MyInterface item)as type MyInterface. When you try to call build(item), it searches for a method with a signature void build(MyInterface item). As you can see, this method does not exist - that’s why you get an error not found by the character.

0
source

All Articles