0

https://docs.oracle.com/javase/tutorial/java/IandI/interfaceDef.html

Ref: Why can't I declare static methods in an interface?

The oracle documentation says you can declare the static method in interface, but if i try to do it in IDE it throws me error. While other posts show that we cannot declare static methods in java? What is correct?

what I am doing wrong?

Community
  • 1
  • 1
piyush
  • 115
  • 2
  • 12
  • 3
    You need Java 8 to allow static methods in an interface. Make sure your IDE knows that you're using Java 8. If you tell us what IDE you're using, then we can give you more specific help. – ajb Dec 08 '14 at 16:53
  • Okay got you,Thanks! i was using java 7. – piyush Dec 08 '14 at 17:00

2 Answers2

3

Which version of java are you using?

Support for static methods in interfaces has been added in Java 8.

alampada
  • 2,329
  • 1
  • 23
  • 18
0

This is a new Java 8 feature along with some more cool tricks. You can define static method, default method as well to avoid too many unwanted code in all implementation classes or make interfaces backward compatible while adding new methods.

Example:

public interface Printer {

//This method must implement by implementation class
public void print(String abc);

//This method may or may override by implementation class
default public void printAll(List<String> list){
    for(String str: list){
        print(str);
    }
}

//This is a static method 
public static void printLog(String str){
    //Do something different 
}

}

You may want to rethink where ever you have abstract classes in your design.

kamoor
  • 2,909
  • 2
  • 19
  • 34