java - null behavior in function overloading with polymorphism -
this question has answer here:
i have 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 static void main(string args[]) { helloworld h = new helloworld(); h.printdata(null); } } and have 2 simple classes
class test { } class newtest extends test { } and output got reached 2
why second function selected executing , not 1st one? when tried same code making class newtest2 extending test , analogous printdata() function gave me compile time error. there rule select function must executed , when?
why second function selected executing , not 1st one?
because method taking newtest more specific method taking test, , both accessible , applicable.
however, when you've got 2 subclasses of test, neither conversion more specific other, hence call ambiguous.
see jls section 15.12.2.5 exact rules involved:
if more 1 member method both accessible , applicable method invocation, necessary choose 1 provide descriptor run-time method dispatch. java programming language uses rule specific method chosen.
the informal intuition 1 method more specific if invocation handled first method passed on other 1 without compile-time type error.
Comments
Post a Comment