Java 8 Interface Default and Static Method

Before Java 8, you can only declare public abstract methods in an Interface. With Java 8, Interface can have static method and default method.

Interface with Static Method and Default Method

MyInterface interface has a default method foo() and static method bar()

1
2
3
4
5
6
7
8
9
10
public interface MyInterface {
default public void foo(){
System.out.println("foo()");
}

public static void bar() {
System.out.println("bar()");
}
}

Implementation

1
2
3
public class MyInterfaceImpl implements MyInterface {
}

static method and default method demo

1
2
3
4
5
6
7
8
public static void main(String[] args) {
// call static method
MyInterface.bar();

// call default method
MyInterface myInterfaceImpl = new MyInterfaceImpl();
myInterfaceImpl.foo();
}

References