微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在Java 9中,接口中的私有方法有哪些规则?

在Java 9中,接口中的私有方法有哪些规则?

Java 9 在接口添加私有方法功能。可以使用private修饰符来定义私有方法。我们可以在Java 9的接口中添加私有私有静态方法

接口中私有方法的规则:

  • 私有方法的主体位于接口意味着我们不能像通常在接口中那样声明为普通的抽象方法。如果我们试图声明一个没有主体的私有方法,那么它可能会抛出一个错误,指出“方法需要主体而不是分号”。
  • 我们不能在接口中同时使用私有抽象修饰符。
  • 如果我们想从接口中的静态方法访问私有方法,那么方法可以声明为私有静态方法,因为我们无法对非静态方法进行静态引用。
  • A 非静态上下文中使用的私有静态方法意味着它可以从接口中的方法调用

interface <interface-name> { private methodName(parameters) { // some statements } }

示例

interface TestInterface {
   default void methodone() {
      System.out.println("This is a Default method One...");
      printValues(); // calling a private method
   }
   default void methodTwo() {
      System.out.println("This is a Default method Two...");
      printValues(); // calling private method...
   }
   private void printValues() { // private method in an interface
      System.out.println("methodone() called");
      System.out.println("methodTwo() called");
   }
}
public class PrivateMethodInterfaceTest implements TestInterface {
   public static void main(String[] args) {
      TestInterface instance = new PrivateMethodInterfacetest();
      instance.methodone();
      instance.methodTwo();
   }
}

输出

This is a Default method One...
methodone() called
methodTwo() called
This is a Default method Two...
methodone() called
methodTwo() called

以上就是在Java 9中,接口中的私有方法有哪些规则?的详细内容,更多请关注编程之家其它相关文章

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐