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

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -