> 文档中心 > 接口中的私有方法

接口中的私有方法

接口中的私有方法

  • 一 由来
  • 二 定义格式
  • 三 注意事项
  • 四 例题讲解

一 由来

java9新增了带方法体的私有方法,这其实在Java8中中就埋下伏笔==:Java8允许在接口中定义带方法的默认方法和静态方法这样可能就会引发一个问题:当两个默认方法或者静态方法中包含一段相同的代码实现时,程序必然考虑将这段实现代码抽象成一个共性方法,而这个共性方法是不需要让别人使用的,因此用私有给隐藏起来了,这就是Java9增加私有方法的必然性。

二 定义格式

  • 格式1: private 返回值类型 方法名(参数列表){}
  • 范例1: private void show(){}

三 注意事项

  • 默认方法可以调用私有的静态方法和非静态方法
  • 静态方法只能调用私有的静态方法

四 例题讲解

  • 定义一个接口Inter,里面有四个方法,二个默认方法,两个静态方法

default void show1(){}
default void show2(){}

static void method1(){}
static void method1(){}

  • 定义接口的一个实现类:
    InterImpl

  • 定义测试类:
    InterDemo
    在主方法中,按照多态的方式创建对象并使用
    Inter接口

package Demo;public interface Inter {    //两个默认方法show1和show2    default void show1(){ System.out.println("show1是默认方法");// System.out.println("iKun");// System.out.println("开团");// System.out.println("鸡你太美"); show(); show0();    }    default void show2(){ System.out.println("show2是默认方法");// System.out.println("iKun");// System.out.println("开团");// System.out.println("鸡你太美"); show(); show0();    }    //两个为静态方法show3和show4    static void show3(){ System.out.println("show3是静态方法"); System.out.println("iKun"); System.out.println("开团"); System.out.println("鸡你太美"); show00();    }    static void show4(){ System.out.println("show4是静态方法"); System.out.println("iKun"); System.out.println("开团"); System.out.println("鸡你太美"); show00();    }    //定义一个私有的静态方法和动态方法    private void show(){ System.out.println("iKun"); System.out.println("开团"); System.out.println("鸡你太美");    }    private static void show0(){ System.out.println("iKun"); System.out.println("开团"); System.out.println("鸡你太美");    }    //定义一个私有的静态方法    private static void show00(){ System.out.println("iKun"); System.out.println("开团"); System.out.println("鸡你太美");    }}

InterImpI实现类

package Demo;public class InterImpI implements Inter {//当然实现类里面可以写默认方法}

InterDemo测试类

package Demo;public class InterDemo {    public static void main(String[] args) { Inter i=new InterImpI(); i.show1(); System.out.println("---------------------------------"); i.show2(); System.out.println("---------------------------------"); Inter.show3(); System.out.println("---------------------------------"); Inter.show4();    }}

输出的内容:
show1是默认方法
iKun
开团
鸡你太美


show2是默认方法
iKun
开团
鸡你太美


show3是静态方法
iKun
开团
鸡你太美


show4是静态方法
iKun
开团
鸡你太美

进程已结束,退出代码为 0