This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
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

Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Basic Constructor doubt" Watch "Basic Constructor doubt" New topic

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

Joined: Jul 08, 2003
Posts: 24168

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:
subject: Basic Constructor doubt
Similar Threads
object stream
byte array to String
Java array and String problem
primitive conversion