• Post Reply Bookmark Topic Watch Topic
  • New Topic

why not method(Object)  RSS feed

 
Suresh K Babu
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, Can any body please explain me why method(Integer) is called for method(null)?
public class A{
public static void main(String... arg){
A returnType = new A();
A.method(null);
}
public void method(Object obj){
System.out.println("Object is called");
}
public void method(Integer longvalue){
System.out.println("Integer is called");
}
}

output:-
Integer is called.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Search around for the term "most specific". This question has been asked and answered a couple of times before.
 
Wouter Oet
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please UseCodeTags. You made a mistake when copying it: A.method(null); should be returnType.method(null);.

That is because Java always called the most specialized method. And because Integer is more specialized then Object (Integer extends Object) the Integer function is called. For fun add a function with a Double argument.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!