Home> Java> javaTutorial> body text

What are the rules for private methods in interfaces in Java 9?

WBOY
Release: 2023-08-31 12:57:11
forward
1249 people have browsed it

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

Java 9 addsprivatemethodsnew features ininterface. Private methods can be defined using theprivatemodifier. We can addprivateandprivatestaticmethodsin the interface of

Java 9

Rules for private methods in interfaces:

  • Having the body of a private method in the interface means that we cannot declare it as a normal abstract method as we usually do in interfaces. If we try to declare a private method without a body, then it may throw an error saying "This method requires a body and not a semicolon".
  • We cannot useprivateandabstractmodifiers simultaneously in an interface.
  • If we want to access a private method from a static method in the interface, then the method can be declared asPrivate static methodbecause we cannot make a static reference to anon-staticmethod .
  • AA private static methodused in anon-staticcontext means that it can be called from thedefault methodin the interface.

Syntax

interface  { private methodName(parameters) { // some statements } }
Copy after login

Example

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(); } }
Copy after login

Output

This is a Default method One... methodOne() called methodTwo() called This is a Default method Two... methodOne() called methodTwo() called
Copy after login

The above is the detailed content of What are the rules for private methods in interfaces in Java 9?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!