File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Null passed into constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Null passed into constructor" Watch "Null passed into constructor" New topic
Author

Null passed into constructor

Kamil Dada
Ranch Hand

Joined: Aug 07, 2001
Posts: 43
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

Joined: May 05, 2000
Posts: 13974
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


Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Thanks Thomas!
I was not clear about this either.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Null passed into constructor