• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Bear Bibeault
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Jj Roberts
  • Tim Holloway
  • Piet Souris
Bartenders:
  • Himai Minh
  • Carey Brown
  • salvin francis

Null passed into constructor

 
Ranch Hand
Posts: 43
  • 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
 
mister krabs
Posts: 13974
  • 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
 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Thomas!
I was not clear about this either.
 
Die Fledermaus does not fear such a tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic