my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Some doubt about Method calling Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Some doubt about Method calling" Watch "Some doubt about Method calling" New topic
Author

Some doubt about Method calling

shashi nela
Greenhorn

Joined: May 24, 2006
Posts: 23

output is String. How is it possible?
Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 9427
    
    2

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.


SCJP 1.4, SCWCD 1.4 - Hints for you, Certified Scrum Master
Did a rm -R / to find out that I lost my entire Linux installation!
Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 9427
    
    2

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

Joined: Dec 20, 2006
Posts: 3
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?


be nice
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

See our SCJP FAQ: What is a most-specific method?


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
y mashalkar
Greenhorn

Joined: Dec 20, 2006
Posts: 3
Gotcha!
thnx!
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Some doubt about Method calling