DEV Community

loading...

Default methods in Java 8

Ravi Yasas
Software Engineer by profession. Author of https://javafoundation.xyz
・1 min read

The problem

interface Automobile{
    void engineStart();
    void engineStop();
}

class Car implements Automobile{
    public void engineStart() { }
    public void engineStop() { }
}

class Bus implements Automobile{
    public void engineStart() { }
    public void engineStop() { }
}
Enter fullscreen mode Exit fullscreen mode
  • Just think we need to add another method in the interface in the future.
  • But if we add it, we have to change all other classes which are implemented that interface.

Default methods

  • To overcome this, default methods are introduced in Java 1.8
  • The interface segregation principle can be replaced with default methods in Java.
  • This is the best option to change the existing interfaces without changing implemented classes.
  • Until Java 1.7 every method inside an interface is always public and abstract.
  • In 1.8 version default and static methods are also allowed.
  • In 1.9 version private methods are also allowed.
  • Default methods can be overridden in implementing class.
  • Default methods cannot be overridden object class's methods.

The solution using Java 8 default methods

interface Automobile{
    default void m1(){}
}

interface Car{
    default void m1(){}
}

class Mazda3 implements Automobile, Car{
    public void m1() { }
}
Enter fullscreen mode Exit fullscreen mode
  • In such cases you have to override the default method.
  • Otherwise Mazda3 class won't be able to find which m1( ) method needs to be called.

Or else you can use it like this also using the "super" keyword.

interface Automobile{
    default void m1(){}
}

interface Car{
    default void m1(){}
}

class Mazda3 implements Automobile, Car{
    public void m1() {
        Automobile.super.m1();    
    }
}
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

Forem Open with the Forem app