polymorphism - Behavior of method overloading in java -
this question has answer here:
- two methods same name in java 3 answers
i tried following code
public class helloworld { public void printdata(test t) { system.out.println("reached 1"); } public void printdata(newtest t) { system.out.println("reached 2"); } public void printdata(newtest1 t) { system.out.println("reached 3"); } public static void main(string args[]) { test t1 = new test(); helloworld h = new helloworld(); h.printdata(t1); newtest t2 = new newtest(); h.printdata(t2); newtest1 t3 = new newtest1(); h.printdata(t3); test t4 = new newtest(); h.printdata(t4); test t5 = new newtest1(); h.printdata(t5); } }
and have simple classes
class test { } class newtest extends test { } class newtest1 extends test { }
and output got is
reached 1 reached 2 reached 3 reached 1 reached 1
from output looks when jvm decides function execute takes consideration only type of reference , not actual type of object.
why happen? why can't jvm take consideration type of actual object rather type of reference pointing it?
function overloading compile time polymorphism , here compiler decide version of method called.for compiler it's difficult know actual object run time check reference type irrespective of object it's going point.
Comments
Post a Comment