my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Which one is come 1'st ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of JavaScript Promises Essentials this week in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Which one is come 1 Watch "Which one is come 1 New topic
Author

Which one is come 1'st ?

rex tony
Ranch Hand

Joined: Aug 29, 2007
Posts: 159
Hello,
Good morning to all.In my class has a 2 constructor with one argument,in which one constructor argument is object and then another constructor argument is string.At this synario i create a instace for that class pass null argument.Which one is excute.
I'm getting the answer is String argument.
Why the Object argument doesn't excute the first, cause Object all for the base class.
What is reason
Even as i wrote this sample code as well
-----------------
class sample
{
sample(Object o)
{
System.out.println("Object");
}
sample(String o)
{
System.out.println("String");
}


}

class constructor
{
public static void main(String arg[])
{
sample s1=new sample(null);
}
}

regards
rex
Jaideep Kshirsagar
Greenhorn

Joined: Aug 29, 2007
Posts: 27
This may be because null is considered a special datatype by JAVA.
Abdullah Mamun
Ranch Hand

Joined: Mar 19, 2007
Posts: 99

Hi rex tony

Originally posted by :
...I'm getting the answer is String argument.
Why the Object argument doesn't excute the first, cause Object all for the base class.
What is reason...


The reason is, for an argument type, when more than one method is found as a candidate for calling then JVM chooses the most specific one and call that method. In this example, for null value, method with String and Object argument type are both candidate for calling. Since String is more specific than Object(i.e. String extends Object) so method with String argument gets called.


MooN
Lalit Bansal
Ranch Hand

Joined: Jan 29, 2007
Posts: 63
Moreover if you have the following code:

class sample
{
sample(Object o)
{
System.out.println("Object");
}
sample(String o)
{
System.out.println("String");
}
sample(Integer o)
{
System.out.println("Integer");
}
}

class constructor
{
public static void main(String arg[])
{
sample s1=new sample(null);
}
}


In this case you shall get the following compiler error. The reason being compiler cannot choose which constructor to call between
'sample(String o)' & 'sample(Integer o)' as because both String and Integer are child classes of class Object.

The compiler shall play safe only till it has only one specific class. As soon as it finds two classes both of which are eligible, it shall throw a compiler error.

Hope this gives you a better and clearer picture.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Which one is come 1'st ?