Java 8: Default methods

  Java Features     Java 5     Java 7     Java 8  
Java 8 features
 Lambda expressions |   Method references |   Default methods |   forEach loop |   By date 

The feature default methods is included in JSE8. This feature allows you to add new defalut methods to your interfaces and ensure that the classes, which implement the interface remain compatible with the new code. It is not mandatory to override default methods unlike abstract methods. For more info click here to read Oracle’s explanation.

Example 1: Default methods in interfaces

What is written to the standard output as the result of executing the following code?
MsInterface.java

public interface MsInterface
{
  // Abstract method
  void getMessage(String msg);
  // Default method
  default void writeMessage()
  {
    System.out.print("I feel ");
  }
}

Mc.java

 
public class Mc implements MsInterface
{
  // overriding abstract method
  public void getMessage(String msg)
  {
    System.out.print(msg);
  }
  public static void main(String[] args)
  {
    Mc mc = new Mc();
    // invoking default method
    mc.writeMessage();
    // invoking abstract method
    mc.getMessage("good!");
  }
}
Author: Sar Maroof

Answer explanation

  1. The statement  mc.writeMessage(); invokes the default method writeMessage.
  2. The statement System.out.print(“I feel “); writes ‘I feel’ to the standard output.
  3. The statement mc.getMessage(“good!”); invokes the method getMessage, which is overridden in the class MyClass.
  4. The statement System.out.print(msg); writes ‘good’ to the standard output.

The answer is: I feel good!

 





Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply

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