Java SE 8: Implementing Default Methods in Interfaces

Overview

Purpose

This tutorial covers how to use default methods in an interface in the Java Platform, Standard Edition 8 (Java SE 8) environment.

Time to Complete

Approximately 45 minutes

Introduction

Prior to Java SE 8, interfaces in Java could contain only method declarations and no implementations, and any nonabstract class implementing the interface had to provide the implementation. This limitation made it almost impossible to extend the existing interfaces and APIs. To overcome this limitation, a new concept, called default methods, is introduced in Java SE 8. The default methods are fully implemented methods in an interface, and they are declared by using the keyword default. Because the default methods have some default implementation, they help extend the interfaces without breaking the existing code.

In this tutorial, you learn how to use default methods in interfaces:

  • Create a Java SE 8 project
  • Extend interfaces without the default method
    • Develop implementation classes
    • Extend the interface
  • Extend interfaces with the default method
  • Understand the inheritance rules of the default methods
  • Test the project

Hardware and Software Requirements

The following is a list of hardware and software requirements:

  • Download and install the latest JDK from this link (Java SE 8u11 recommended).
  • Download and install NetBeans 8 with Java SE from this link. JUnit is an optional installation and is not required for this tutorial.

Prerequisites

Before starting this tutorial, you should:

  • Have installed the required software.
  • Ensure that NetBeans is running.

Creating a Java Project

In this section, you create a Java SE 8 application in the NetBeans IDE.

  1. Select File > New Project.

  2. In the New Project dialog box, perform the following steps on the Choose Project page:

    1. Select Java from Categories.
    2. Select Java Application from Projects.
    3. Click Next.
  3. On the Name and Location page, perform the following steps:

    1. Enter DefaultMethods as the project name.
    2. Click Finish.

    The DefaultMethods project is created in NetBeans.

Extending Interfaces Without Default Methods

In this section, you develop an interface, MyService, and add an abstract method, myDuties(). You develop two implementation classes, Developer and Tester, which implement the MyService interface. You develop a Java class, RoleTester, to test the application. Finally, you extend the MyService interface by adding another method, extraDuties().

Developing the Interface

In this section, you develop a MyService interface and add an abstract method, myDuties().

  1. On the Projects tab, right-click DefaultMethods and select New > Other.

  2. In the New File dialog box, perform the following steps on the Choose File Type page:

    1. Select Java from Categories.
    2. Select Java Interface from File Types.
    3. Click Next.
  3. On the Name and Location page, perform the following steps:

    1. Enter MyService as the class name.
    2. Enter com.example as the package name.
    3. Click Finish.
  4. Modify the MyService interface by entering the following to add an abstract method, myDuties():

         public void myDuties();

Developing the Implementation Classes

In this section, you develop two implementation classes, Developer and Tester.

  1. On the Projects tab, right-click DefaultMethods and select New > Other.

  2. In the New File dialog box, perform the following steps on the Choose File Type page:

    1. Select Java from Categories.
    2. Select Java Class from File Types.
    3. Click Next.
  3. On the Name and Location page, perform the following steps:

    1. Enter Developer as the class name.
    2. Enter com.example as the package name.
    3. Click Finish.
  4. Repeat steps 1 through 3 to create the Tester class.

Modifying the Implementation Classes

In this section, you modify the Java classes to implement the following:

  • MyService interface
  • myDuties() method
  1. Modify the Developer class.

    1. Have the class implement the MyService interface as follows:
    2. public class Developer implements MyService{

      }

      The compiler generates an error because the Developer class must implement the myDuties()abstract method of the interface.

    3. Implement the myDuties()method by adding the following line of code:
    4. System.out.println("I will develop the application");

      The compiler error is resolved now.

  2. Modify the the Tester class.

    1. Have the class implement the MyService interface as follows:
    2. public class Tester implements MyService{

      }

      The compiler generates an error because the Tester class must implement the myDuties() abstract method of the interface.

    3. Implement the myDuties()method by adding the following line of code:
    4. System.out.println("I will test the application");


      The compiler error is resolved now.

Testing the Application

In this section, you develop the RoleTesting class to test the application.

  1. On the Projects tab, right-click DefaultMethods and select New > Other.

    alt description here
  2. In the New File dialog box, perform the following steps on the Choose File Type page:

    1. Select Java from Categories.
    2. Select Java Class from File Types.
    3. Click Next.
    alt description here
  3. On the New Java Class page, perform the following steps:

    1. Enter RoleTester as the class name.
    2. Enter com.example as the package name.
    3. Click Finish.
    alt description here
  4. Add the main() method to the class.

    public static void main(String[] args) {

    }

    alt description here
  5. Add the following lines of code to the main() method:

    Developer Tim=new Developer();
    Tim.myDuties();

    alt description here

    The code creates an instance of the Developer class and invokes the myDuties method of the Developer class.

  6. Add the following lines of code to the main() method:

      Tester Jim = new Tester();
     Jim.myDuties();

    alt description here

    The code creates an instance of Tester class and invokes the myDuties method of the Tester class.

  7.  Right-click RoleTester.java and select Run File.

    alt description here
  8. Verify the output in the output console.

    The myDuties() method of the specific classes are invoked for both Developer and Tester classes.

Extending the MyService Interface

In this section, you extend the MyService interface by adding another abstract method, extraDuties(). The application breaks. That is, a compiler error is generated when this method is added to the interface, because the new method should be implemented by all implementation classes. Therefore, the implementation classes, Developer and Tester, have to implement this new extraDuties() method.

Perform the following steps to extend the MyService interface:

  1. On the Projects tab, double-click MyService.java to open it in the editor.

  2. Add the extraDuties() method.

    alt description here
  3. Save MyService.java. Observe the compiler error in Developer.java and Tester.java.

    alt description here

The compiler error was generated because the Developer and Tester classes do not implement the extraDuties() method defined in the MyService interface. Before Java SE 8, interfaces in Java could contain only method declarations and no implementations, and any nonabstract class implementing the interface had to provide the implementation. This limitation made it almost impossible to extend the existing interfaces and APIs. To overcome this limitation, in the next section, you will use default methods in the interface.

Extending Interfaces with Default Methods

In this section, you add a default method to the MyService interface. You modify the extraDuties method as a default method by adding a keyword, default, to the method. Next you modify the Developer class to implement the default extraDuties method. You modify the RoleTester class by invoking the default method on instances of the Tester and Developer classes and observe the output.

  1. Modify MyService.java. Perform the following steps: 

    1. Add the default keyword to the method signature.
    2. default public void extraDuties()
         {
             System.out.println("perform extra duties");
         }

      alt description here
    3. Save MyService.java. Observe that the compiler errors are resolved.
  2. Modify Developer.java by adding the following code to implement the default method, extraDuties():

     public  void extraDuties() {
            System.out.println("I will perform extra duties for my service");
     }

    alt description here

    The Tester class has not implemented the extraDuties() method.

  3. Modify RoleTester.java.

    1. Add the following line of code to the main() method:
    2. Tim.extraDuties();

      alt description here

      This line of code invokes the extraDuties() method of the Developer class.

    3. Add the following line of code to the main() method:
    4. Jim.extraDuties();

      alt description here

      This line of code invokes the extraDuties() method of the MyService interface because the Tester class has not implemented the extraDuties() method.

  4. Test the application: Right-click RoleTester.java and select Run File.

    alt description here
  5. Verify the output in the console.

    alt description here
    The Developer class is providing its own implementation of extraDuties(), whereas, on the other side, the Tester class did not provide any implementation for the extraDuties()method. The Tester implementation invoked the default method of the extraDuties() provided by the interface.

Implementing Inheritance Rules of Default Methods

In this section, you implement one of the inheritance methods of default methods. That is, if the method names conflict, the default method should be treated as the default. The concrete class must provide its own implementation of the method.

You develop another interface, MyNewService, with a default method, extraDuties(). You modify the Developer and Tester classes to implement the two interfaces, MyService and MyNewService, and each interface declares a default method with the same name, extraDuties(). The result is a compiler error to avoid the confusion of which default method to be invoked. Finally, you modify the classes to implement the default method.

Developing the MyNewService Interface

  1. On the Projects tab, right-click DefaultMethods and select New > Other.

  2. In the New File dialog box, perform the following steps on the Choose File Type page:

    1. Select Java from Categories.
    2. Select Java Interface from File Types.
    3. Click Next.
  3. On the Name and Location page, perform the following steps:

    1. Enter MyNewService as the class name.
    2. Enter com.example as the package name.
    3. Click Finish.
  4. Modify the interface, MyNewService, by adding a default method, extraDuties().

         default  public void extraDuties()
       {
           System.out.println("perform extra duties from the new service");
       }

Modifying the Implementation Classes

  1. Modify the Developer class.

    1. Have the class implement the MyNewService interface as follows:
    2. public class Developer implements MyService,MyNewService {

          public void myDuties() {
              System.out.println("I will develop the application");
             
          }

        
      }

      The compiler generates the following error, "Duplicate default methods named extraDuties with the parameters () and () are inherited from the types MyNewService and MyService". The solution for this error is to implement the extraDuties() method in the implementing class,Developer.

    3. Implement the extraDuties()method as follows:
    4.   public void extraDuties() {
              System.out.println("I will perform extra duties for my new service");

          }

      The compiler error is resolved.

  2. Modify the Tester class.

    1. Have the class implement the MyNewService interface as follows:

      public class Tester implements MyService,MyNewService {

          public void myDuties() {
              System.out.println("I will test the application");
          }

        
      }

      The compiler generates the following error, "Duplicate default methods named extraDuties with the parameters () and () are inherited from the types MyNewService and MyService".The solution for this error is to implement the extraDuties() method in the implementing class,Tester.

    2. Implement the extraDuties()method as follows:

        public void extraDuties() {
              System.out.println("I will perform extra duties for my new service");

          }

      The compiler error is resolved.

  3. Test the application by right-clicking RoleTester.java and selecting Run File.

  4. Verify the output in the console.

    The output is invoked from the overridden extraDuties method of the respective implementation classes.

Summary

In this tutorial, you learned to:
  • Create a Java SE project
  • Extend interfaces without the default method
    • Develop implementation classes
    • Extend the interface
  • Extend interfaces with the default method
  • Implement the inheritance rules of the default methods
  • Test the project

Resources

Credits

  • Curriculum Developer: Anjana Shenoy
  • Editor: Susan Moxley
  • QA: Krishnanjani Chitta

To navigate this Oracle by Example tutorial, note the following:

Topic List:
Click a topic to navigate to that section.
Expand All Topics:
Click the button to show or hide the details for the sections. By default, all topics are collapsed.
Hide All Images:
Click the button to show or hide the screenshots. By default, all images are displayed.
Print:
Click the button to print the content. The content that is currently displayed or hidden is printed.

To navigate to a particular section in this tutorial, select the topic from the list.