• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Calling Overloading Method

 
saravanan saminathan
Greenhorn
Posts: 19
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
I hav eone doubt regarding function overloading in java. I have two methods with same name, but with different parameters.Like
methodA(Object obj)
methodA(String str)
When calling these methods if i pass null as parameter then methodA(String) is called. Why it is calling String parameter methid instead of Object paramter methd?. Can anyone clarrify me?.

Thanks in Advance
S.Saravanan.
 
gkumar kumar
Greenhorn
Posts: 8
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

String is an object and its not primitive data type.
StringBuffer is intialized using constructor

Ex: StringBuffer sb = new StringBuffer("Hello");
but String can be
String str="Hello" or
String str=new String("Hello");
This is the adv of string class compared to other classes.
Similarly Object is a class like StringBuffer.
methodA(null) means it will call String only
if methodA(new Object()) it will call Object
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by saravanan saminathan:
Hi All,
I hav eone doubt regarding function overloading in java. I have two methods with same name, but with different parameters.Like
methodA(Object obj)
methodA(String str)
When calling these methods if i pass null as parameter then methodA(String) is called. Why it is calling String parameter methid instead of Object paramter methd?. Can anyone clarrify me?.

Thanks in Advance
S.Saravanan.

Is this a question for distributed java?
Please choose the forums properly before posting.
Probably moderators will pounce on this and move to an appropriate forum !!
However, answering your question,
Whenever, there is an ambiguity in resolving a method based on the argument type, the method with the most derived type will be called i.e if Child extends Base, then always method with Child as argument will be called in case of an ambiguity.
However, if you have methods with parameters at the same level in the inheritance hierarchy, i.e Child1 extends Base and Child2 extends Base, and you call method with null, the compiler will throw an exception saying ambiguous method call.
 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Probably moderators will pounce on this and move to an appropriate forum !!




Yes... moving this to the Java In General (Intermediate) forum.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic