This week's book giveaway is in the JavaFX forum.
We're giving away four copies of Introducing JavaFX 8 Programming and have Herbert Schildt on-line!
See this thread for details.
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 Introducing JavaFX 8 Programming this week in the JavaFX forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Confusing contructor call" Watch "Confusing contructor call" New topic

Confusing contructor call

Puneet Nayyar

Joined: Feb 02, 2006
Posts: 18

I am confused regarding the output of the following code:

Class ABC{
ABC(Object o){
ABC(String s){

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

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

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.

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

Joined: Feb 02, 2006
Posts: 18

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?

Anupam Sinha
Ranch Hand

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

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

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

    I agree. Here's the link:
    subject: Confusing contructor call
    It's not a secret anymore!