java1.8 novel properties (a) Interface default method

A Profile

   We usually refer to the role of an interface is used to define a set of criteria, constraints, and other specifications, method declarations interface only signature methods, to provide a corresponding method thereof, a method thereof to achieve a corresponding implementation classes.

In JDK1.8 a break this understanding, the method interface method body may have, but need to modify the default or static keyword is used to modify the static call static methods, static methods to call through the interface name, use default modified method is referred to as the default, the default method is called by the object instance. 

The role of static methods and the default method:

   Static method and the default body has its own method for providing a default implementation, this sub-class to implement the method does not need to force, can choose to use a default implementation, may be rewritten own implementation. When the interface is an extension method, you only need to provide a default implementation of this method can be, as for the corresponding implementation class can override the default implementation can also be used, so that all the implementation class does not report a syntax error: Xxx not abstract, and of abstract methods Yxx uncovered.

Two examples

interface:

Package com.swpu.newJDk; 

public  interface DefaultInterface {
    public    int K = 10 ;
     void the commonMethod ();
     default  void defaultMethod () { 
        System.out.println ( "default interface method" ); 
    } 
    static  void STATICMETHOD () { 
        the System .out.println ( "static interface method" ); 
    } 
}

test:

Package com.swpu.newJDk; 

/ ** 
 * @ClassName the Test 
 * @Description the TODO 
 * @author Wangxu Long 
 * @date 2019/9/9 14:53 
 * / 

public  class the Test {
     public  static  void main (String [] args) { 
anonymous // implementation class DefaultInterface defaultInterface
= new new DefaultInterface () { @Override public void the commonMethod () { System.out.println ( "common interface previous methods, need to be rewritten" ); } }; defaultInterface.commonMethod (); defaultInterface .defaultMethod (); DefaultInterface .staticMethod (); System.out.println(DefaultInterface.k); } }

result:

Results show that:

 When calling interface name in static modification of staticMethod the method can not be called directly by example objects. Call the modified method with default instance of an object, the interface is a member variable public static final modification directly

Guess you like

Origin www.cnblogs.com/wxl1640326208/p/11491990.html
Recommended