This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Null passed into constructor

 
Kamil Dada
Ranch Hand
Posts: 43
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I happened to come across this interesting code:
1 class sample
2 {
3 sample(String s)
4 {
5 System.out.println("String");
6 }
7 sample(Object o)
8 {
9 System.out.println("Object");
10 }
11 }
12 class constructor
13 {
14 public static void main(String arg[])
15 {
16 sample s1=new sample(null);
17 }
18 }
The answer was: Program compiles correctly and prints "string" when executed
Why is this?
And also, there was another question:
1 class sample
2 {
3 sample(String s)
4 {
5 System.out.println("String");
6 }
7 sample(StringBuffer sb)
8 {
9 System.out.println("StringBuffer");
10 }
11 }
12 class constructor
13 {
14 public static void main(String arg[])
15 {
16 sample s1=new sample(null);
17 }
18 }
And here the answer was: Compile time error as call to constructor at line no. 16 is ambigious.
Why is this?
And can someone please be so kind as to explain these two programs to me?
Thank You
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The JLS actually covers this. Here's a rundown.
When there is an ambiguous case, it will always pick the one furthest down the hierarchy. So in the first one, String is a child of Object so it picks String. In the second case, neither is further down the hierarchy than the other so it can't pick between String and StringBuffer.
------------------
Tom - SCJP --- Co-Moderator of the Programmer Certification Forums
 
Anonymous
Ranch Hand
Posts: 18944
  • 0
  • send pies
  • Quote
  • Report post to moderator
Thanks Thomas!
I was not clear about this either.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic