File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overloading

 
umang bhartia
Ranch Hand
Posts: 60
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi every 1
Please let me know that why the code given below is printing "Sting called". I thought that it should give either compile time error or should print "Object called".
public class Obj
{
public Obj(Object o)
{
System.out.println("Object called");
}

public Obj(String s)
{
System.out.println("String called");
}
public static void main(String[] args)
{
Obj o = new Obj(null);
}
}
 
bill bozeman
Ranch Hand
Posts: 1070
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This has been discussed before so you may be able to go to older posts to get more eloborate answers. But here is my thinking, null is a keyword, a "null" literal.
There are 4 different versions of this you can try.
1. Have only the Object constructor: you get "Object" printed.
2. Have two constructors, one with Object and the other any other ojbect, and you get the other object
3. Have two constuctors, one with Object and the other with a primitive, and you ghet "Object" printed
4. Have two constrocuts, any objects other than Object, and you get a compile time error for ambiguous constructors.
This shows null is an object, remember for instance varibles if they are not initialized they are set to null, and it will only call object references. Since all objects extend Object, a call is made to the lowest class on the hierarchy. If there are two unrelated objects, then a compile error is made because it doesn't know who to call.
Try this out, it may help

This prints out Mutt since that is the lowest on the chain.
Throw in a method that takes String as an argument and you get a compile time error.
Bill
 
umang bhartia
Ranch Hand
Posts: 60
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Bill,
That was really great of u for explaining it with eg. now i m clear with this. U r right, it takes the lowest in the chain. thanks once again.
 
Khurram Fakhar
Ranch Hand
Posts: 65
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Null is always considered as String , while passing as an arguments ..
plz correct me if i m wrong

Regards
Khurram
 
bill bozeman
Ranch Hand
Posts: 1070
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Khurram, I don't think it is based on the code above. Since I do not have a method taking String as an argument, it still works so I don't think null is considered a string. From the JLS they say true and false are string literals, but null is a null literal.
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic