Private interface methods, example use-case?

后端 未结 3 1021
借酒劲吻你
借酒劲吻你 2020-12-30 19:36

\"Support for private methods in interfaces was briefly in consideration for inclusion in Java SE 8 as part of the effort to add support for Lambda Expressions, but was with

3条回答
  •  礼貌的吻别
    2020-12-30 20:11

    Java 9 allows declaring a private method inside the interface. Here is the example of it.

    interface myinterface {
        default void m1(String msg){
            msg+=" from m1";
            printMessage(msg);
        }
        default void m2(String msg){
            msg+=" from m2";
            printMessage(msg);
        }
        private void printMessage(String msg){
            System.out.println(msg);
        }
    }
    public class privatemethods implements myinterface {
        public void printInterface(){
            m1("Hello world");
            m2("new world");
        }
        public static void main(String[] args){
            privatemethods s = new privatemethods();
            s.printInterface();
        }
    }
    

    For that, you need to update jdk up to 1.9 version.

提交回复
热议问题