Static methods & Default Methods in Java 8

An interface describes what a class should look like but not describe how, closely related to class but can’t be instantiated. Before Java 8. Java interface can have abstract method (without method definition) only, but Java 8 onwards, two new features were introduced namely Default method and Static method within interface.

Default Method

-A default method allows to add a new methods in existing interface without affecting the implementing classes.

-It uses default modifier

– It must have a complete method definition. Basically, a dummy body.
– It is not compulsory for implementing class to override a default method but one can.

Reason to introduce it

Prior to Java 8, a class that implements an interface mandatorily had to provide implementation to abstract methods of that particular interface.

However, it was not a big deal, but Java developers noticed that if there is an existing interface which has implemented by quite a large number of classes and there a need arises of adding another method. Then it would need to be overridden by other classes. This would break the code if any of the class omit to implement it.

Therefore, default method came in to picture, now one can add any new feature to existing interface without affecting behaviour of other implementing classes.

Problem:

Before adding new Feature:

No error

After adding new Feature:

error 3

 

Solution

For example:

interface MyInterface {
    default void display() {
        System.out.println("This is dummy definition");
    }
}

public class DefaualtMethodExample implements MyInterface {

    public static void main(String[] args) {
        DefaualtMethodExample obj = new DefaualtMethodExample();
        obj.display();
    }
}

Output:

This is dummy definition

Static method

– Java 8 also supports static method within an interface.

-Method body should be provided to the static method at the time of its declaration.

-It can’t be overridden in implementing classes

-It uses static modifier

– By default, static methods cannot be available in implementing classes. Therefore one need to call it by InterfaceName.methodName()

 

For example:

interface MyInterface {
    static void display() {
        System.out.println("This is static definition");
    }
}

public class DefaualtMethodExample implements MyInterface {

    public static void main(String[] args) {
        MyInterface.display();
    }
}

Output:

This is static definition

 

Leave a Reply