How to implement Default methods in java8?

     It is one of the features included in java8. A default method is one can be implemented by the interface. If you want to add more implementations further without breaking the existing structure of interface.

It has following features.

  • ·       The method is implemented with some functionality.
  • ·       Even, after the default method implementation, you can add more methods. It is called backward compatibility.
  • ·       Multiple inheritance is possible.
  • There are many ways to use default methods.

Here, we use two types.

A simple way of implementing Dafault method:

  • Create an interface “TstInterface” and add a void method “rectangle” with two arguments (Length and breadth).
  • Write the code for finding area of triangle by the formula (l*b).
  • TstClass is the class which implements the interface.
  • There, include the code for void function implementation.
  • Create an object for class. Call the two functions using objects.

interface TstInterface {

void rectangle(int l,int b);

default void area() {

System.out.println("This program executed Default Method");

}

}

class TstClass implements TstInterface {

public void rectangle(int l,int b) {

System.out.println("The area of rectangle is : "+l * b);

}

public static void main(String args[]) {

TstClass d = new TstClass();

d.rectangle(4,6);

d.area();

}

}

The output is given below.

C:\raji\blog>javac TstClass.java

C:\raji\blog>java TstClass

The area of rectangle is : 24

This program executed Default Method

2.Overriding a Default method:

              Overriding is a concept of redefining a implementation. Here, two interfaces and 2 methods with same name. both of the interfaces are implemented by  a class.

For overriding, the keyword “super” is used.

//Java Program to Override a defult method

interface Interface1 {

    default void myMethod() {

        System.out.println("This message shows Interface1 implementation");

    }

}

interface Interface2 {

    default void myMethod() {

        System.out.println("This message shows Interface2 implementation");

    }

}

public class MyClass implements Interface1, Interface2 {

    @Override

    public void myMethod() {

        Interface1.super.myMethod();  // or Interface2.super.myMethod();

    }

    public static void main(String[] args) {

        MyClass ob = new MyClass();

        ob.myMethod();  // This will call the overridden method

    }

}

Just compile and run the program, you will get the output.

C:\raji\blog>javac MyClass.java

C:\raji\blog>java MyClass

This message shows Interface1 implementation

These are the ways to implement default methods in java.

No comments:

Post a Comment