2

I thought you can not override static method in Java but its not a compile time error to declare exactly same method in sub class, That is called method hiding in Java. But what if i have to override static method.

// filename Test.java
public class Test { 
  public static void foo() { 
    System.out.println("Test.foo() called "); 
  } 
  public static void foo(int a) { 
    System.out.println("Test.foo(int) called "); 
  } 
  public static void main(String args[]) { 
    Test.foo(); 
    Test.foo(10); 
  } 
} 
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
user3171412
  • 101
  • 7
  • 2
    What happened when you tried it? – Elliott Frisch Apr 27 '14 at 03:07
  • Give us a case where you HAVE to override a static method? – Lokesh Apr 27 '14 at 03:08
  • possible duplicate of [Why doesn't Java allow overriding of static methods?](http://stackoverflow.com/questions/2223386/why-doesnt-java-allow-overriding-of-static-methods) – SimonT Apr 27 '14 at 03:09
  • This seems like it may be a [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – Elliott Frisch Apr 27 '14 at 03:11
  • 1
    class Base { // Static method in base class which will be hidden in subclass public static void display() { System.out.println("Static or class method from Base"); } public void print() { System.out.println("Non-static or Instance method from Base");}} // Subclass class Derived extends Base { public static void display() { System.out.println("Static or class method from Derived");} public void print() { System.out.println("Non-static or Instance method from Derived"); – user3171412 Apr 27 '14 at 03:17
  • Next time dont copy and paste just a question from the internet just for receiving up votes! Try and do a research and try to learn from this research. Your question is exactly the same with the 10th question of this page: http://www.java67.com/2012/09/top-10-tough-core-java-interview-questions-answers.html – Fotis Grigorakis Jul 28 '17 at 07:00

1 Answers1

2

You can't override static methods in Java, because, polymorphism and static won't work together. And static methods are invoked on Class, not in instances.

You can hide a super class static method in sub class.

Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105