Krzysztof Antoniak
Krzysztof Antoniak

Reputation: 451

Call overloaded method using template

There are three classes, ChildChild, Child and Parent one extending another. I call method using template for most outer class and I would like to get method doSomething called to print "CHILD". Instead of that previous method gets called.

class Test {
    public <T extends Parent> void doSomething(T input) {
        System.out.println("PARENT");
    }
    public <T extends Child> void doSomething(T input) {
        System.out.println("CHILD");
    }

    public <T extends Parent> void run(T input) { doSomething(input); }
}

class Main {
    public static void main(String[] args) {
        Test t = new Test();
        t.run(new ChildChild());
    }
}

Is that because of method run defining template only for Parent class?

Upvotes: 1

Views: 53

Answers (1)

Eran
Eran

Reputation: 393841

Yes, when the compiler erases the generic type parameters, they are replaced by their type bounds, so your run method becomes :

public void run(Parent input) { doSomething(input); }

and the overloaded methods become :

public void doSomething(Parent input) {
    System.out.println("PARENT");
}
public void doSomething(Child input) {
    System.out.println("CHILD");
}

Therefore doSomething(Parent input) is called (remember that method overloading resolution is determined at compile time, using the compile-time types), regardless of the runtime type of the instance you are passing to the run method.

Upvotes: 2

Related Questions