piyush
piyush

Reputation: 115

Can i declare static method in interface?

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?

Upvotes: 0

Views: 116

Answers (2)

kamoor
kamoor

Reputation: 2939

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.

Upvotes: 0

alampada
alampada

Reputation: 2409

Which version of java are you using?

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

Upvotes: 3

Related Questions