• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Confusing contructor call

 
Puneet Nayyar
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am confused regarding the output of the following code:

Class ABC{
ABC(Object o){
System.out.println("Object");
}
ABC(String s){
System.out.println("String");
}

public static void main(String[] args){
new ABC(null);
}
}

When i am running this class i am getting the output as
>String

Can anyone explain me why the constructor with argument as Object is getting neglected when i am calling the constructor with argument value as null?

Any help would be appreciated.

Thanks,
Puneet
 
Ganesh Kumar
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi puneet,

When you declare a variable as string with out intializing it, it will have "null" as a value in it.So when you pass null as a value string constructor will get invoked.Have you got cleared??
 
Puneet Nayyar
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Thanks for the reply Ganesh but still its unclear.
You are saying that When we declare a String like
String s
then we get a null String object
Same should be the case when i declare
Object o
it should also give a null object.

So the confusion is still there?

Thanks
Puneet
 
Anupam Sinha
Ranch Hand
Posts: 1090
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java would choose the closest match. That is, let say you have a String and StringBuffer constructor/method. Now both are not related to each other apart from the fact that both have a common parent/grandparent Object. So in this case when you pass null compiler would not be able to decide which invocation of the method/constructor is asked for. But in case you have a hierarchy, the one who is closest to the reference type is chosen.
 
Raghavan Muthu
Ranch Hand
Posts: 3381
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Puneet,

Its because of the closest-match found by the compiler. Please go through the following threads, they may help you.

  • What is the most specific method?
  • Passing null to the method argument - thread



  • HtH.
     
    Puneet Nayyar
    Greenhorn
    Posts: 18
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thanks all!!
    I got the concept.

     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic