aspose file tools*
The moose likes Beginning Java and the fly likes Overriding a static method in Java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Overriding a static method in Java" Watch "Overriding a static method in Java" New topic
Author

Overriding a static method in Java

rahul deo
Greenhorn

Joined: Jul 05, 2011
Posts: 10
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

Joined: Oct 13, 2005
Posts: 38765
    
  23
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

Joined: Apr 06, 2010
Posts: 4387
    
    8

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

Joined: Jul 05, 2011
Posts: 10
Thanks Campbell. now i understood..:-)
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38765
    
  23
Well done
 
 
subject: Overriding a static method in Java