java8 new features four - the default method

Brief introduction

Java 8 new default interface methods.

Simply put, the default method is the interface can be implementation, and do not need to go to achieve its implementation class method.

We just in front of the method name to add a default keyword can be realized default method.

 

Why should this feature?

First, before the interface is a double-edged sword, for the benefit is not facing the specific programming abstraction, defects, when the need to modify the interfaces, the need to modify the entire class that implements the interface, a set of current frame is not the previous 8 java foreach method, solutions usually can think of is to add new methods to the relevant interfaces in the JDK and implementation. However, the version has been released, there is no way to give an interface to add new methods without affecting existing implementations. So the default method of introduction. Their purpose is to solve modify the existing implementation of the interface incompatibility problems.

 

grammar

The default method syntax is as follows:

public  interface Vehicle {
    default  void Print () { 
      System.out.println ( "I am a car!" ); 
   } 
}

Multiple default method

Interface has a default method, consider the case, a plurality of class implements interfaces, and has the same default of these interfaces, the following examples illustrate the solution to this situation:

 /**
     * 字符串分割接口
     */
    interface StrSubitFun{
        String subString(String inStr,int startIndex);
        default void  test(){
            System.out.println("strsub test");


        }
    }

    interface testDe{
        default void test(){
            System.out.println("testDe test");
        }
    }

    class testSubDe implements StrSubitFun,testDe{
        @Override
        public String subString(String inStr, int startIndex) {
            return null;
        }
        @Override
        public void test() {

        }
    }

    class testSubDe1 implements StrSubitFun,testDe{
        @Override
        public String subString(String inStr, int startIndex) {
            return null;
        }
        @Override
        public void test() {
            StrSubitFun.super.test();
        }
    }

This means that if the same default method appears, subclass must be rewritten.

Guess you like

Origin www.cnblogs.com/wish5714/p/11334931.html
Recommended