java - Call overloaded method using template -
there 3 classes, childchild
, child
, parent
1 extending another. call method using template outer class , method dosomething
called print "child". instead of 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 because of method run defining template parent class?
yes, when compiler erases generic type parameters, replaced type bounds, run
method becomes :
public void run(parent input) { dosomething(input); }
and 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)
called (remember method overloading resolution determined @ compile time, using compile-time types), regardless of runtime type of instance passing run
method.
Comments
Post a Comment