Email address:
Password:
SCJP/OCPJP 1.6 certification
Practice Exams and Training
SCJP Online Training » Discussions

Not able to understand how constructor is called in this case "Integer In"

public class Lanka{
    public Lanka(Object o){
      System.out.println("Object In");
    }
    public Lanka(Integer o){
      System.out.println("Integer In");
    }
    public Lanka(Number o){
      System.out.println("Number In");
    }
    public static void main(String args[]){
      new Lanka(null);
    }
}

Taking the given three methods individually, you can pass null to any of them. However, when it comes to method overloading, where there are several matching methods for a null value to be passed to, it will actually invoke the method that has the parameter which is the sub-most type.


In the hierarchy, we know that Object stays at the top. Then we know that Number is a sub-type of Object (because Number extends Object). Similarly, Integer is a sub-type of Number (because Integer extends Number). In that hierarchy, Integer is the sub-most type, so that's the parameter this null value will go for.

But if I add one more constructor


public Lanka(String o){
   System.out.println("String In");
}


or

public Lanka(Float o){
   System.out.println("Integer In");
}


or

public Lanka(Double o) {
   System.out.println("Integer In");
}


In that case its giving me Compile time Error?

That's correct! Because by doing that, you are making the compiler unable to find a sub-most type.


Think about the original program, which had only Object, Integer, and Number. In that program, all three types were in the same hierarchy root, and so you can easily tell which one is the sub-most type - Integer:


But when you add another overloaded version with String as the parameter, you are making a separate branch, making it's impossible to tell which one is the sub-most type.


As you can see above, Integer and String both qualify as sub-most types. Since the compiler cannot determine which of these two methods to invoke, it gives you a compile error.



Same happens when you try to add a method which as Float or Double as the parameter type.



As you can see above, both Integer and Float/Double qualify as the sub-most type, making the compiler unable to decide which one to invoke.


Does that make it clearer?

Sure it does. Thanks a lot

ExamLab © 2008 - 2024