[Java from the beginning to the end] No10.JDK1.8 Interface

JDK1.8 interface composition update

1 Overview

  • First of all, before JDK1.8, there were only two components in the interface.

1.abstract methodThe default modifier is public abstract
2.constantThe default modifier is public static final

  • The following components were added in JDK1.8

1.Default methodThe modifier is the keyword default , which is a non-abstract method with a method body. The implementation class of the interface can choose to implement it or not. It is not mandatory. If it is not implemented, the default is the implementation logic in the interface, so it is called default. Methods can facilitate the expansion of the interface.
2.static methodThe modifier is naturally static

  • Private methods were added in JDK1.9

1.private methodThe modifier is naturally private . In JDK 1.8, the syntax for writing private methods in interface classes was passable, but the execution would report an error. Private methods were officially introduced in JDK 1.9, because when we can write specific processing logic in the interface At this time, there must be common code blocks that need to be proposed to become common private processing logic methods.

2.Code

  • Default method
public interface NewInterface {
    
    

    // java8之前,接口中只包含如下两个内容
    // 1.常量:默认修饰符为 public static final
    int a = 1;

    //2. 抽象方法:默认修饰符为 public abstract
    void method();

    // 在java8的时候在接口中可以写默认方法和静态方法了
    // 首先,默认方法
    public default String methodDefault() {
    
    
        return "default method";
    }

    // 以及静态方法
    public static void methodStatic() {
    
    
        System.out.println("static method in interface");
    }

    // 以及在java9中可以写私有方法了
    private void methodPrivate() {
    
    
        System.out.println("private method in interface");
    }

}

Guess you like

Origin blog.csdn.net/cjl836735455/article/details/108696716