3

Can any one explain?

When we are overloading a constructor with different parameters one having data type object and other having data type string, and when we are creating the object of this class with providing input parameter as null it is calling the constructor with string as input parameter but not the constructor having input parameter as Object. Since Object is the super class of String, can any one tell me why it is calling constructor with input parameter string?

Class A
{
  public A(Object o)
   {
     System.out.println("Object Drawn");
   }
   public A (String o)
   {
     System.out.println("String Drawn");
   }
   public static void main(String args[])
   {
   new A(null);
   }
 }

Output:- String Drawn

10
  • 1
    This is either a C++ question or a Java question, but not both. It looks to be Java, so why the c++ tag? Commented Sep 8, 2012 at 7:33
  • I took the liberty to remove the C++ flag. Commented Sep 8, 2012 at 7:34
  • 2
    I don't see how the language matters given the answer is the same. Commented Sep 8, 2012 at 7:35
  • 2
    @PeterLawrey: That is obvious. As someone experienced with C++, I can't confidently answer a question about Java, so the tag wastes the time of C++-only people like me; and no-one coming here looking for the C++ answer who didn't already know the two languages behave the same way in this respect could draw any useful information about C++ from it. Commented Sep 8, 2012 at 7:38
  • 1
    @PeterLawrey the answer is not the same in c++. Since A us being constructed with null, the only possible C++ equivalent is to make the constructors take a pointer to Object and String, and calling A(nullptr) would result in a compilation error due to an ambiguous overload. Commented Sep 8, 2012 at 8:49

1 Answer 1

4

It always calls the most specific matching method or constructor. If it didn't you would always call Object and overloading it would be pointless.

This approach is using in Java and C++

Sign up to request clarification or add additional context in comments.

2 Comments

Is it so because the null string "" is more appropriate? And is there something as a null object?
If you use "" it is definitely an empty String. If you use null is can be either a String or an Object. The term "null string" and "null object" is just confusing and there is no standard value for this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.