Java 8 Feature – Default Method in Interface

Default method can be written in Interface from Java 8 onwards.

This feature is included to support the new functionality addition in the existing interface by maintaining backward compatibility. That means classes which have already implemented corresponding interfaces won’t be impacted.

Default methods helps to provide default implementation of the methods which either can be changed by the implementing Class or can be used as it is.

Example –

Java Program –

package com.thinkconstructive;

interface DefaultMethodExample
{
    default void methodOne(){
        System.out.println("Default Method One");
    }
    default void methodTwo(){
        System.out.println("Default Method Two");
    }
}

class ExampleClass implements DefaultMethodExample
{
}

public class DemoDefaultMethod {
    public static void main(String args[])
    {
        DefaultMethodExample defaultMethodExample = new ExampleClass();
        defaultMethodExample.methodOne();
        defaultMethodExample.methodTwo();
    }
}

Output of the above program –

Default Method One
Default Method Two

In the above example, DefaultMethodExample is an Interface with 2 default methods. This Interface is implemented by ExampleClass. Finally both the default methods are called by main class. Methods definition given in interface gets executed and corresponding output gets printed.

When an Interface extends another Interface which has default method Resulted Interface inherits the default method

Example –

package com.thinkconstructive;

interface DefaultMethodExample
{
    default void methodOne(){
        System.out.println("Default Method One");
    }
    default void methodTwo(){
        System.out.println("Default Method Two");
    }
}

class ExampleClass implements DefaultMethodExample
{
}

interface NewInterface extends DefaultMethodExample
{
}

class ExampleNewClass implements NewInterface
{
}

public class DemoDefaultMethod {
    public static void main(String args[])
    {
        DefaultMethodExample defaultMethodExample = new ExampleClass();
        defaultMethodExample.methodOne();
        defaultMethodExample.methodTwo();

        NewInterface newInterface = new ExampleNewClass();
        newInterface.methodOne();
        newInterface.methodTwo();
    }
}

Output –

Default Method One
Default Method Two
Default Method One
Default Method Two

In the above example, NewInterface implements DefaultMethodExample Interface which already has 2 default methods. Both the default methods are inherited by NewInterface. NewInterface Interface is implemented by ExampleNewClass. Finally both the default methods are called by main class. Methods definition given in interface gets executed and corresponding output gets printed.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *