美文网首页Java相关技术
Java 9新增的语法特性概览

Java 9新增的语法特性概览

作者: zenny_chen | 来源:发表于2017-10-30 00:18 被阅读43次

Java 9刚发布不久,新增的Java语法特性并不多,这里笔者感觉比较实用的就是允许在接口中定义私有成员方法,这样可以更方便地实现当前接口的模块性封装。下面我将展示一些简单的代码进行描述。

package com.company;
import org.jetbrains.annotations.Contract;


interface MethodFunction {
    void call(int i);
}

interface MyInterface {
    public void hello();

    @Contract(pure = true)
    private int method(int i) {
        return i + 1;
    }

    final int aa = 200;

    static MyInterface hi(MyInterface mi) {
        int x = aa + mi.method(50);
        System.out.println("Hi, there! x = " + x);
        return mi;
    }
}


public class Main {

    public static void main(String[] args) {
        // write your code here

        MyInterface.hi(new MyInterface() {
            @Override
            public void hello() {
                System.out.println("Hello, world!!");
            }
        }).hello();

        System.out.println("aa = " + MyInterface.aa);

        MethodFunction ref = (i) -> {
            System.out.println("This lambda param is: " + i);
        };

        ref.call(100);

        ref = Main::Hello;
        ref.call(20);

        Main m = new Main();
        ref = m::method;
        ref.call(10);
    }

    private static void Hello(int i) {
        System.out.println("i = " + i);
    }

    private void method(int i) {
        System.out.println("method i = " + i);
    }
}

上述代码比较简单,由于接口的私有成员方法只能作用于该接口自身,因此不能直接在实现它的类中进行直接访问。但我们可以通过在此接口中定义一个类方法,以对象传递的方式进行访问,这么一来正好可以形成针对当前接口的一种闭环设计。当然,private 也能修饰接口中的类方法。

相关文章

网友评论

    本文标题:Java 9新增的语法特性概览

    本文链接:https://www.haomeiwen.com/subject/pgiupxtx.html