interpretation of null by JVM
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Abbas_Muhammad
Posted On:   Monday, January 30, 2006 03:50 PM

public class Test { public Test(){System.out.println("Default");} public Test(String s){System.out.println("string");} public Test(Object o){System.out.println("object");} public static void main(String[] args) { new Test(null); } } When we execute the above code we get the following answer string The question here is why does the JVM displays "string" and not "default" when the most close match of the argument for the constructor is the first one. Can anyone please elaborate the reason for this behavior Thanks    More>>
			
public class Test
{

public Test(){System.out.println("Default");}

public Test(String s){System.out.println("string");}

public Test(Object o){System.out.println("object");}


public static void main(String[] args)

{
new Test(null);

}

}





When we execute the above code we get the following answer

string



The question here is why does the JVM displays "string" and not "default" when the most close match of the argument for the constructor is the first one. Can anyone please elaborate the reason for this behavior
Thanks

   <<Less

Re: interpretation of null by JVM

Posted By:   WarnerJan_Veldhuis  
Posted On:   Monday, January 30, 2006 05:17 PM

That answer is simple: because the constructor invoked is Test(x) with ONE parameter... Test() has NO parameters, so that is NOT going to be invoked in a million years....(Unless you specify this() )



The real WTF is why it's not displaying "object"... Reason: The JVM is going to look for the best specified parameter. Since String inherits from Object, it's the most specific and gets invoked. If you would have a constructor called Test(Character c) AND Test(String s) the compiler would complain since it cannot determine the most specific declared method (String and Character both inherit from Object, so they are considered the same "level".
About | Sitemap | Contact