Pregunta

Hello I have an issue with polymorphism.

In general I think I have understood what it means. I added a MWE below.

I expected that I get two times teh text Using String on the console. In fact I get both texts once. Why?

The reason is I want to create a pattern like the visitor pattern and I want to avoid chains of if( ... instanceof ... ). Therefore I thought I implement for each type a method (here String and Object) that are overloaded.

The question is now how to make java select the correct method.

PS: The reason I have this problem is that I have to 'box' the elementary types into classes for furthe use. Therefore I have to test for Integer, Boolean, ... This is also the reason why I cannot simple extend the class and use a common method.

public class TestOverload
{
    public static void main(String[] args)
    {
        String s = "abc";
        Object o = s;

        TestOverload test = new TestOverload();
        test.doSomething(s);
        test.doSomething(o);
    }

    public void doSomething(Object o)
    {
        System.out.println("Using Object");
    }

    public void doSomething(String s)
    {
        System.out.println("Using String");
    }
}
¿Fue útil?

Solución

In java virtual machine, methods are determined with their names, argument types, and and return type. This is why two or more methods with the same name can coexist - because their "full names" are different. Java compiler selects most appropriate method to call so that minimal argument type conversion required (and disregards the return type). So it selects doSomething(String s) for the first case anddoSomething(Object o) for the second. At run time, methods selected at compile time are invoked, so the actual type of Object o does not matter.

If you box simple types into Integer and Boolean, there is no other way to determine the actual type except for instanceof. Consider boxing into your own types which can be extended.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top