Java 8 Static and Default Methods

Java 8 Static and Default Methods

Default Method: For backward-compatibility.

To invoke a default method using the interface name, you can use the interfaceName.super.defaultMethod() syntax, like this:

interface MyInterface { 
default void defaultMethod() {
 System.out.println("This is a default method."); 
} 
} 
class MyClass implements MyInterface {
public void callDefaultMethod() { MyInterface.super.defaultMethod(); 
} 
} 
MyClass myObject = new MyClass(); myObject.callDefaultMethod(); // Output: "This is a default method."

Static Method: For utility method.

To invoke a static method using the interface name, you can use the interfaceName.staticMethod() syntax, like this:

interface MyInterface {
    static void staticMethod() {
        System.out.println("This is a static method.");
    }
}

class MyClass {
    public void callStaticMethod() {
        MyInterface.staticMethod();
    }
}
MyClass myObject = new MyClass();
myObject.callStaticMethod(); // Output: "This is a static method."
//interface variables or static variables of interface can also be accessed using Interface name directly like MyInterface.variableName.