Default and Static methods in Java 8 Interfaces

Before Java 8, interfaces could only have abstract methods and constants. Java 8 allows you to have default as well as static methods inside an interface. This was mainly done for interface unlocking: Now you can add methods to an interface without needing the implementing classes to change.

 

Default methods

You can add an instance method to an interface through the keyword default.

They are also public similar to the abstract methods. 

Default methods are inherited by subclasses and can be overriden.

You can have multiple default methods within an interface.

 

Example:

public interface I {

  void m1();

  default void m2(){

    m1();

  }

}

 

TODO:

Add examples for:

  1. Inheriting and overriding default methods.

  2. Multiple default methods.

  3. What happens during Muliplie inheritance? How is diamond problem handled?

 

Static methods

Static methods will not be able to access instance methods. 

Static methods can be accessed through interface names just as any static method is accessed using class name.

Example:

public interface I {

void m1();

static void m2(){

}

 

TODO:

Add examples for:

  1. Inheriting static methods and hiding them.

Search the Web

Custom Search

Searches whole web. Use the search in the right sidebar to search only within javajee.com!!!