File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes static method overriding in same class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "static method overriding in same class" Watch "static method overriding in same class" New topic

static method overriding in same class

Pratap gogireddy

Joined: Dec 03, 2011
Posts: 7

hi friends

I got this question in one of the MNC written exam

class abctest
static void m1(Object o){System.out.println("Hello Object!");}
static void m1(String s){System.out.println("Hello String!");}
public static void main(String[] args)

when i test on the System the OUTPUT is Hello String

Why it takes String Method instead of Object Method can any one explain for me please

Thanks in advance....
Riaan Nel
Ranch Hand

Joined: Apr 23, 2009
Posts: 160

As far as I know, Java takes the most specific method that it can find.

null is valid for any Object, including a String. Hence, the String method is called.

<nitpick>You're referring to overloading, not overriding.</nitpick>

"The reasonable man adapts himself to the world; the unreasonable one persists in trying to adapt the world to himself. Therefore, all progress depends on the unreasonable man." - George Bernard Shaw
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46349
That is more than a nitpick. If people think they can override static method, or fields, they will get all sorts of errors with the wrong member of a class being used.
Claudiu Chelemen
Ranch Hand

Joined: Mar 25, 2011
Posts: 74

Similar topic here, you may want to check Steve's reply.

Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15082

The example you give is overloading, not overriding.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Thomas Kennedy
Ranch Hand

Joined: Jan 20, 2008
Posts: 137
This is overloading, not overriding, as others have pointed out. I will add that my understanding is that, strictly speaking, there is no such thing as overriding a static method. An override happens at runtime, when the jvm, which already knows the signature of the method to be invoked (that's recorded by the compiler), figures out what object to invoke the method on. So if you had this:

Because statics are invoked on the class, there is nothing for the jvm to decide, and so no override is taking place here.

Costs matter. Justice lies in processes not outcomes. Crime is caused by criminals.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46349
. . . but it would be different if you wrote
I agree. Here's the link:
subject: static method overriding in same class
It's not a secret anymore!