aspose file tools*
The moose likes Beginning Java and the fly likes Confusing contructor call Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Confusing contructor call" Watch "Confusing contructor call" New topic
Author

Confusing contructor call

Puneet Nayyar
Greenhorn

Joined: Feb 02, 2006
Posts: 18
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

Joined: Jul 02, 2007
Posts: 113
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

Joined: Feb 02, 2006
Posts: 18
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

Joined: Apr 13, 2003
Posts: 1088
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

Joined: Apr 20, 2006
Posts: 3344

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.


    Everything has got its own deadline including one's EGO!
    [CodeBarn] [Java Concepts-easily] [Corey's articles] [SCJP-SUN] [Servlet Examples] [Java Beginners FAQ] [Sun-Java Tutorials] [Java Coding Guidelines]
    Puneet Nayyar
    Greenhorn

    Joined: Feb 02, 2006
    Posts: 18
    Thanks all!!
    I got the concept.

     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: Confusing contructor call