0

Java static methods can be overridden but without any use because it calls the base class method only. So what is the use of defining a static method in an interface?

public interface Foo {

  public static int bar() {
    ...

}
}

1.The interface can not be instantiated

2.Even if it doesn't shows any error while inheriting it finds no practical use:

Ex:

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");
    }

     // Non-static method which will be overridden in derived class 
     public void print()  {
         System.out.println("Non-static or Instance method from Base");
    }
}

// Subclass

class Derived extends Base {

    // This method hides display() in Base 
    public static void display() {
         System.out.println("Static or class method from Derived");
    }

    // This method overrides print() in Base 
    public void print() {
         System.out.println("Non-static or Instance method from Derived");
   }
}

Output:

Static or class method from Base

Non-static or Instance method from Derived

Jens
  • 67,715
  • 15
  • 98
  • 113
Sourav Saha
  • 153
  • 2
  • 12
  • 2
    possible duplicate of [Why can't I define a static method in a Java interface?](http://stackoverflow.com/questions/512877/why-cant-i-define-a-static-method-in-a-java-interface) – Smutje Jan 26 '15 at 07:38
  • Static methods in a Java interface weren't even *possible* until recently. For very good reasons (per the link cited by Smutje above). Here are more details: http://www.journaldev.com/2752/java-8-interface-changes-static-methods-default-methods-functional-interfaces. – FoggyDay Jan 26 '15 at 07:42
  • You cannot override a static method. In class Derived you have just defined a new method display() – Gren Jan 26 '15 at 15:24
  • I said if we try to override a static method it will not show any error but at the same time it can not be overridden. – Sourav Saha Jan 27 '15 at 17:39

1 Answers1

0

static methods in interfaces were introduced in Java 8 together with default methods. They enable the interface to supply helper methods that can be used to implement the interface methods (either the default implementations that appear in the interface or the implementations that will appear in classes that implement the interface).

Eran
  • 387,369
  • 54
  • 702
  • 768