
是的,我们可以在 Java 9 的接口中拥有私有方法或私有静态方法。可以使用这些方法来去除代码冗余。 私有方法只能在该界面中有用或可访问。我们无法从一个接口访问或继承私有方法到另一个接口或类。
<strong>interface <interface-name> {
private static void methodName() {
// some statements
}
private void methodName() {
// some statements
}
}</strong>interface Java9Interface {
public abstract void method1();
public default void method2() {
method4();
method5();
System.out.println("Inside default method");
}
public static void method3() {
method5(); <strong>// static method inside other static method</strong>
System.out.println("Inside static method");
}
private void method4() { <strong>// private method</strong>
System.out.println("Inside private method");
}
private static void method5() { <strong>// private static method</strong>
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();
}
}<strong>Inside abstract method Inside private method Inside private static method Inside default method Inside private static method Inside static method</strong>
以上就是在Java 9中,我们可以在接口中定义私有方法或私有静态方法吗?的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号