Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
java

How to write an interface with a default method in Java

Sumit Sharma

Why do we need default methods in interfaces?

Like regular interface methods, default methods are automatically made public. This means there’s no need to specify the public modifier.

Unlike regular interface methods, they can now be declared with the default keyword at the beginning of the method. They can also provide an implementation.

According to the old rules of interfaces – where an interface can have one or multiple implementations – all the implementations would have to be forcibly implemented if one or more methods were added to the interface.

Code

Let’s look at the below code snippet to understand this better:

interface xyzInterface {
   // regular interface method
   void regularMethod();
   // default method implementation
   default void defaultMethod() {
       //implemented body
       System.out.println("default method");
   }
}

class myClass implements xyzInterface {
   @Override
   public void regularMethod() {
       System.out.println("regular method");
   }

   @Override
   public void defaultMethod() {
       xyzInterface.super.defaultMethod();
   }
}

class myMain
{
   public static void main(String[] args) {
       myClass myClass= new myClass();
       myClass.regularMethod();
       myClass.defaultMethod();
   }
}
Implementing default method in Java

Explanation

  • In lines 1 to 9, we make an interface with a regular method without a body, as well as a default method with a body.

  • In lines 11 to 20, we implement the interface and override both the regular method and the default method.

  • In lines 23 to 30, we create an object of the implemented class and compare the usage of the regular method and the default method by calling them.

Default interface methods are an efficient way to deal with this problem. They allow us to add new methods to an interface that are implicitly available in the implementations. Thus, there’s no need to modify the implementing classes.

RELATED TAGS

communitycreator
java
RELATED COURSES

View all Courses

Keep Exploring