java - Which overloaded method will execute and why? -
java - Which overloaded method will execute and why? -
this question has reply here:
which overload selected null in java? 3 answers how overloaded methods work? 2 answerspublic class nulldemo { /** * @param args */ public static void main(string[] args) { // todo auto-generated method stub nulldemo n = new nulldemo(); n.execute(null); } public void execute(object o) { system.out.println("object"); } public void execute(double o) { system.out.println("double"); } } i have executed above code , execute method execute(double o).i need know reason why executed execute(double o) , not execute(object o)
and suppose
public class nulldemo { /** * @param args */ public static void main(string[] args) { // todo auto-generated method stub nulldemo n = new nulldemo(); n.method1(null); /// give compilation error } public void method1(float o) { system.out.println("object"); } public void method1(double o) { system.out.println("double"); } } if create method public void method1(float o) , public void method1(double o) give compilation error why so? related hierarchy?
java prefer phone call method furthest downwards inheritance tree. consider next situation:
class demo { public void dosomething(parentclass foo) { //..... } public void dosomething(childclass foo) { //..... } public static void main() { demo demo = new demo(); demo.dosomething(new childclass()); } } in above situation, method phone call can match either of 2 methods. however, can see intuitively should match sec method.
you can read exact behavior in java spec: http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.12.2
java oop method-overloading
Comments
Post a Comment