Win a copy of The Business Blockchain this week in the Cloud forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static method overriding in same class

 
Pratap gogireddy
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....
 
Riaan Nel
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>
 
Campbell Ritchie
Sheriff
Posts: 51332
86
  • 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.
 
Claudiu Chelemen
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
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15627
46
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.
 
Thomas Kennedy
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: 51332
86
  • 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