Why default method?
For example we have an interface which has multiple methods, and multiple classes are implementing this interface. One of the method implementation can be common across the class. We can make that method as a default method, so that the implementation is common for all classes.
Second scenario where we have already existing application, for a new requirements we have to add a method to the existing interface. If we add new method then we need to implement it throughout the implementation classes. By using the Java 8 default method we can add a default implementation of that method which resolves the problem.
Java default methods
Java default methods are defined inside the interface and tagged with default keyword. Default methods are non-abstract methods. We can override default methods to provide more specific implementation.
Example
package com.w3schools; interface Display{ //Default method default void display(){ System.out.println("Hello Jai"); } //Abstract method void displayMore(String msg); } public class DefaultMethods implements Display{ //implementing abstract method public void displayMore(String msg){ System.out.println(msg); } public static void main(String[] args) { DefaultMethods dm = new DefaultMethods(); //calling default method dm.display(); //calling abstract method dm.displayMore("Hello w3schools"); } }
Output
Hello Jai Hello w3schools
Static methods in interfaces are similar to the default methods. The only difference is that we cannot override these methods in the classes that implements these interfaces.
Example
package com.w3schools; interface Display{ //Default method default void display(){ System.out.println("Hello Jai"); } //Abstract method void displayMore(String msg); //Static method static void show(String msg){ System.out.println(msg); } } public class StaticMethodTest implements Display{ //implementing abstract method public void displayMore(String msg){ System.out.println(msg); } public static void main(String[] args) { StaticMethodTest smt = new StaticMethodTest(); //calling default method smt.display(); //calling abstract method smt.displayMore("Hello w3schools"); //calling static method Display.show("Hello Java"); } }
Output
Hello Jai Hello w3schools Hello Java