Saturday, March 3, 2018

Interface Default methods

Until 1.7 version onwards inside interface we can take only public abstract methods and public static final variables (every method present inside interface is always public and abstract whether we are declaring or not).

Every variable declared inside interface is always public static final whether we are declaring or not.
But from 1.8 version onwards in addition to these, we can declare default concrete methods also inside interface, which are also known as defender methods.
We can declare default method with the keyword “default” as follows

default void m1() {
 System.out.println(Default Method);
}

Interface default methods are by default available to all implementation classes. Based on requirement implementation class can use these default methods directly or can override.

Ex:

interface Interf {
           default void m1() {
                System.out.println(Default Method);
            }
   }
   class Test implements Interf {
             public static void main(String[] args) {
                       Test t = new Test();
                       t.m1();
    }
}

Default methods also known as defender methods or virtual extension methods.
The main advantage of default methods is without effecting implementation classes we can add new functionality to the interface (backward compatibility).

Note

We can’t override object class methods as default methods inside interface otherwise we get compile time error.

Ex:

interface Interf {
       default inthashCode() {
            return 10;
       }
}


Compile Time Error

Reason

Object class methods are by-default available to every java class hence it’s not required to bring through default methods.

Thanks for reading. If you like this post please follow us for more updates about technology related updates.

No comments: