aspose file tools*
The moose likes Beginning Java and the fly likes Basic Constructor doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Basic Constructor doubt" Watch "Basic Constructor doubt" New topic
Author

Basic Constructor doubt

Abhi Venu
Ranch Hand

Joined: Jul 09, 2009
Posts: 73



class MyClass
{




MyClass(Object ob)
{


System.out.println(" I belong to constructor one with Object as argument");

}


MyClass(byte[] myarray)
{


System.out.println(" I belong to constructor two with byte array as argument");

}

public static void main(String args[])
{

MyClass obj = new MyClass(null);


}

}


On execution Why does the following code always call the constructor which takes byte array as argument?


when that constructor is commented the constructor which takes object array is used..




A table, a chair, a bowl of fruit and a violin; what else does a man need to be happy?:Einstein
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

The rule is that the compiler picks the "most specific" of all the overloaded methods that could apply. Since byte[] is a subclass of Object, the constructor that takes a byte[] is more specific, so that one is selected.

If the two choices were both Object subclasses -- say, byte[] and String, instead of byte[] and Object -- the code wouldn't compile, as the call would be ambiguous.


[Jess in Action][AskingGoodQuestions]
Abhi Venu
Ranch Hand

Joined: Jul 09, 2009
Posts: 73
Thanks for the prompt reply
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Basic Constructor doubt