• Post Reply Bookmark Topic Watch Topic
  • New Topic

Which construtor gets invoked?  RSS feed

 
Karthick Dharani Vidhya
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I came across this Question in recent times. Considering two Below scenario. In Scenario A, I get a Compile time error but in Scenario B, it compiles fine and runs good.
Can some one tell me why?

SCENARIO A:


There is a COMPILE Time error at Line 3.

SCENARIO B:



Compiles fine and runs good. Second constructor gets invoked. Why?
 
Ogeh Ikem
Ranch Hand
Posts: 180
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
According to Kathy Sierra SCJP 6, when a class has overloaded methods, during method matching, the JVM will select the method with the smallest argument that is wider than the parameter.

In SCENARIO A, Integer and Double both qualify because none of them is wider than the other and they are both wider than the parameter i.e. null, so the compiler complains The constructor TestClass(Integer) is ambiguous.

In SCENARIO B, the compiler is happy because Object is wider than Double. The second constructor runs because the JVM will select the method with the smallest argument that is wider than the parameter.
 
Karthick Dharani Vidhya
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Thanks for the reply. But just out of curiosity in the first scenario I changed the Double to Long, Float and even Hash Map or some other object. Still I get the compilation error. Only if I give Object, it gets resolved.

Any idea why it is so?
 
Ogeh Ikem
Ranch Hand
Posts: 180
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you specify Number and Double, the Double will be chosen because the Number is wider. The compiler must be able to tell which one is wider than the other or else, you'll get compiler error.
 
Karthick Dharani Vidhya
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh yeah. I see it now. Thanks a lot.
 
Ogeh Ikem
Ranch Hand
Posts: 180
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!