• Post Reply Bookmark Topic Watch Topic
  • New Topic

constructor overload  RSS feed

 
Jean Rodrigues
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is more a challenge ...
I was discussing with some friends and we've got a little intriguing piece of code:

Which constructor do you think this code will execute? and Why?
Have fun.
[ April 30, 2003: Message edited by: Jean Rodrigues ]
[ April 30, 2003: Message edited by: Jean Rodrigues ]
 
aadhi agathi
Ranch Hand
Posts: 263
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
any thing that is more specific! in case of "null" then it will complain??? check for related posts somehere in the java forum.
Why??? P in PIE(Polymorphism, Inheritance and Encapsulation)
Basic rule: should able to find a operartion for the method call. (able to find a match between formal and actual parameters)
Note: this belongs to a basic forum!
[ April 30, 2003: Message edited by: aadhi agathi ]
 
Donal Lynch
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why? The behaviour seems to be consistent with the language spec (start at JLS 15.12 and follow the rules).
Why was it surprising? Here's my personal mental model, which turned out to be wrong: I thought the compiler would look at the null literal and go either: this doesn't have any type information, so compile-time error; or: this doesn't have any type information, so assume it's an Object. It looks like the compiler actually goes: this is of a special null type, so it's assignable to any reference type (
JLS 4.1).
 
Jean Rodrigues
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In fact, it executes the constructor that takes String as parameter ...
So, if it's a basic question, why dont u try to explain why???
Have fun.
(BTW. Try to cast null to Object, and you will see it will execute the other constructor ...
[ April 30, 2003: Message edited by: Jean Rodrigues ]
 
Jean Rodrigues
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
BTW.
I already know the answer ... Do not need to look for anything ...
Just wanted to share something I found it's nice to understand and why Java has this behavior with this kind of overloading of constructors.
[ April 30, 2003: Message edited by: Jean Rodrigues ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!