• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

Basic Constructor doubt

 
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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..



 
author and iconoclast
Posts: 24204
44
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for the prompt reply
 
Skool. Stay in. Smartness. Tiny ad:
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic