Tuesday, June 6, 2017

Method overloading using null parameter

Method overloading using null parameter recognizes the method which has the child-most parameter

Test2.java
package com.moore;
public class Test2 {
}

Test3.java
package com.moore;
public class Test3 extends Test2 {
}

Test4.java
package com.moore;
public class Test4 extends Test3 {
}


Test.java
package com.moore;
public class Test {

// null is not an Object. So it is not called.
// https://stackoverflow.com/a/1894291
public static void print(Object obj) {
System.out.println("Object");
}

public static void print(Test2 obj) {
System.out.println("test 2");
}

public static void print(Test3 obj) {
System.out.println("Test 3");
}

public static void print(Test4 obj) {
System.out.println("Test 4");
}

public static void main(String[] args) {
Test.print(null);
}
}

it printed out Test 4

Just like in your scenario, this means that if a method is overloaded (and when null is passed), it recognizes the method which has the child-most parameter.

Resource Link: https://stackoverflow.com/a/13133290

No comments:

Post a Comment