• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Basic Constructor doubt

 
Abhi Venu
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



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..



 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Abhi Venu
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the prompt reply
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic