
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What are the advantages of private methods in an interface in Java 9?
In Java 9, an interface can also have private methods. Apart from static and default methods in Java 8, this is another significant change as it allows the re-usability of common code within the interface itself.
In an interface, there is a possibility of writing common code on more than one default method that leads to code duplication. The introduction of private methods avoids this code duplication.
Advantages of private methods in an interface
- Avoiding code duplication.
- Ensuring code re-usability.
- Improving code readability.
Syntax
interface interfacename { private methodName(parameters) { // statements } }
Example
interface Test { default void m1() { common(); } default void m2() { common(); } private void common() { System.out.println("Tutorialspoint"); } } public class PrivateMethodTest implements Test { public static void main(String args[]) { Test test = new PrivateMethodTest(); test.m1(); test.m2(); } }
Output
Tutorialspoint Tutorialspoint
Advertisements