Win a copy of Java by Comparison (eBook) this week in the Java in General forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

static method overriding in same class  RSS feed

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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)
{
m1(null);
}
}

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....
 
Ranch Hand
Posts: 160
IntelliJ IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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>
 
Sheriff
Posts: 57797
178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 75
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Similar topic here, you may want to check Steve's reply.

Cheers,
Claudiu
 
Java Cowboy
Sheriff
Posts: 16081
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The example you give is overloading, not overriding.
 
Ranch Hand
Posts: 137
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Sheriff
Posts: 57797
178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
. . . but it would be different if you wrote
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!