Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overriding a static method in Java

 
rahul deo
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All

I have a little confusion. I Know that we can not override a static method. It will give compilation error.But once i tried a program to override ,it was working fine.
So Please let me know where I am wrong.. Thanks in advance.

class A{
public static void itsMineMethod()
{

System.out.println("its mine work");
}
}
public class B extends A{
public static void itsMineMethod() //This is the overloaded method.
{

System.out.println("its mine inside CheckInterface");
}

public static void main(String[] args)
{
//
}
}

How it is completely valid and will not give error..
 
Campbell Ritchie
Sheriff
Pie
Posts: 48985
60
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your code is difficult to read without the code tags.
You cannot override a static method, but you can hide it. Start by reading our FAQ.
 
Matthew Brown
Bartender
Posts: 4567
8
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's an enhanced example that shows that it's being hidden, not overridden.



The output will be:
This is in the subclass
This is in the superclass


The first line shows that line A is calling the version in the subclass, as expected.

but the second line shows that line B causes the version in the superclass to be called. This is because callMyMethod is in the superclass, so it's calling the version there - static calls are resolved at compile time. But with overridden the version called depends on the actual type of the object, and this is resolved at runtime. If there was genuine overriding going on, "This is in the subclass" would be printed twice.
 
rahul deo
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Campbell. now i understood..:-)
 
Campbell Ritchie
Sheriff
Pie
Posts: 48985
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well done
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic