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
- The statement mc.writeMessage(); invokes the default method writeMessage.
- The statement System.out.print(“I feel “); writes ‘I feel’ to the standard output.
- The statement mc.getMessage(“good!”); invokes the method getMessage, which is overridden in the class MyClass.
- The statement System.out.print(msg); writes ‘good’ to the standard output.
The answer is: I feel good!
Suggested Articles
![]() ![]() ![]() |