003 Interface enhancement

I. Overview

Before jdk8, only abstract methods could be defined in our interfaces.

In jdk8, we can also define static methods and default methods.


 

2. Examples

public  interface Enhance {
     // Default method 
    default  void run() {
        System.out.println("default run .... ");
    }
    // Static method 
    static  void staticMethod() {
        System.out.println("static method run...");
    }
}

An interface as above is defined, which contains default methods and static methods.

In the future, in our subclasses, we can use the default method directly.

And static methods, we can call directly through the name of the interface.

See the test code below:

    @Test
     public  void test() {
         // Call the static method 
        Enhance.staticMethod();
         // Call the default method 
        new Enhance() {}.run();
    }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325066596&siteId=291194637