Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Some doubt about Method calling

 
shashi nela
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

output is String. How is it possible?
 
Joe Harry
Ranch Hand
Posts: 10124
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This has been asked many times. The compiler chooses the most specific method for the job and here the most specific is the one that takes String argument. The rule for choosing the most specific method is that, one method is more specific than the other if any argument that the methodtakes can be easily passed to the other method without any compilation errors. Here any argument that you can pass to a String can be passed to the method that takes Object as argument. But the vice versa is not true. Hence you get this O/P as String.

Hope this helps.
 
Joe Harry
Ranch Hand
Posts: 10124
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Trying this from Dan Chisholm,

class GFC200 {}
class GFC201 {
static void m(Object x) {System.out.print("Object");}
static void m(String x) {System.out.print("String");}
static void m(GFC200 x) {System.out.print("GFC200");}
public static void main(String[] args) {m(null);}
}

Will give you compiler error. Try to find out the reason by yourself.
 
y mashalkar
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I still did not get your point...

i tried this one...

class A
{
static void b(Object obj)
{
System.out.println("Object");
}
static void b(A obj)
{
System.out.println("String");
}
public static void main(String[] args)
{
b(null);
}
}

it did compile...and printed the same answer "String"
How?
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See our SCJP FAQ: What is a most-specific method?
 
y mashalkar
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gotcha!
thnx!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic