我们可以在Java 9的接口中使用私有方法或私有静态方法吗?
是的,我们可以在Java9的接口中使用私有 方法 或私有静态方法。我们可以使用这些方法来消除代码冗余。私有 方法 只能在该接口内有用或可访问。我们不能从一个接口访问或继承私有方法到另一个接口或类。
语法
interface <interface-name> {
private static void methodName() {
//一些陈述
}
private void methodName() {
//一些陈述
}
}示例
interface Java9Interface {
public abstract void method1();
public default void method2() {
method4();
method5();
System.out.println("Inside default method");
}
public static void method3() {
method5(); // static method inside other static method System.out.println("Inside static method");
}
private void method4() { // private method System.out.println("Inside private method");
}
private static void method5() { // private static method System.out.println("Inside private static method");
}
}
public class PrivateStaticMethodTest implements Java9Interface {
@Override
public void method1() {
System.out.println("Inside abstract method");
}
public static void main(String args[]) {
Java9Interface instance = new PrivateStaticMethodTest();
instance.method1();
instance.method2();
Java9Interface.method3();
}
}输出结果
Inside abstract method Inside private method Inside private static method Inside default method Inside private static method Inside static method
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿