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");
}
}