Previous version of Java 8
Before Java 8, the interface seems to only allow two types of data, one is a constant, the other is a public (public) virtual method (abstract), and it is a virtual method Oh, there is no implementation method, because these methods must be implemented by classes. In other words, there are no methods with default implementation in versions before Java 8.
Let’s take a look at an example,
public class InterfacePrivateMethodTester { public static void main(String []args) { LogOracle log = new LogOracle(); log.logInfo(""); log.logWarn(""); log.logError(""); log.logFatal(""); LogMySql log1 = new LogMySql(); log1.logInfo(""); log1.logWarn(""); log1.logError(""); log1.logFatal(""); } } final class LogOracle implements Logging { @Override public void logInfo(String message) { getConnection(); System.out.println("Log Message : " + "INFO"); closeConnection(); } @Override public void logWarn(String message) { getConnection(); System.out.println("Log Message : " + "WARN"); closeConnection(); } @Override public void logError(String message) { getConnection(); System.out.println("Log Message : " + "ERROR"); closeConnection(); } @Override public void logFatal(String message) { getConnection(); System.out.println("Log Message : " + "FATAL"); closeConnection(); } @Override public void getConnection() { System.out.println("Open Database connection"); } @Override public void closeConnection() { System.out.println("Close Database connection"); } } final class LogMySql implements Logging { @Override public void logInfo(String message) { getConnection(); System.out.println("Log Message : " + "INFO"); closeConnection(); } @Override public void logWarn(String message) { getConnection(); System.out.println("Log Message : " + "WARN"); closeConnection(); } @Override public void logError(String message) { getConnection(); System.out.println("Log Message : " + "ERROR"); closeConnection(); } @Override public void logFatal(String message) { getConnection(); System.out.println("Log Message : " + "FATAL"); closeConnection(); } @Override public void getConnection() { System.out.println("Open Database connection"); } @Override public void closeConnection() { System.out.println("Close Database connection"); } } interface Logging { String ORACLE = "Oracle_Database"; String MYSQL = "MySql_Database"; void logInfo(String message); void logWarn(String message); void logError(String message); void logFatal(String message); void getConnection(); void closeConnection(); }
The running results are as follows
$ javac InterfacePrivateMethodTester.java && java InterfacePrivateMethodTester
Open Database connection
Log Message : INFO
Close Database connection
Open Database connection
Log Message : WARN
Close Database connection
Open Database connection
Log Message : ERROR
Close Database connection
Open Database connection
Log Message : FATAL
Close Database connection
Open Database connection
Log Message : INFO
Close Database connection
Open Database connection
Log Message : WARN
Close Database connection
Open Database connection
Log Message : ERROR
Close Database connection
Open Database connection
Log Message : FATAL
Close Database connection
In this example, each type of log has its own implementation
What is the biggest pitfall? Each method must be implemented once. Yes, each method must implement
JDK 8 version
And Java 8 has finally made some changes. The interface in Java 8 can have the following types of variables and methods
1. Constant
2. Virtual method
3. Default method
4. Static method
Let’s change the above example , using the features of Java 8
public class InterfacePrivateMethodTester { public static void main(String []args) { LogOracle log = new LogOracle(); log.logInfo(""); log.logWarn(""); log.logError(""); log.logFatal(""); LogMySql log1 = new LogMySql(); log1.logInfo(""); log1.logWarn(""); log1.logError(""); log1.logFatal(""); } } final class LogOracle implements Logging {} final class LogMySql implements Logging {} interface Logging { String ORACLE = "Oracle_Database"; String MYSQL = "MySql_Database"; default void logInfo(String message) { getConnection(); System.out.println("Log Message : " + "INFO"); closeConnection(); } default void logWarn(String message) { getConnection(); System.out.println("Log Message : " + "WARN"); closeConnection(); } default void logError(String message) { getConnection(); System.out.println("Log Message : " + "ERROR"); closeConnection(); } default void logFatal(String message) { getConnection(); System.out.println("Log Message : " + "FATAL"); closeConnection(); } static void getConnection() { System.out.println("Open Database connection"); } static void closeConnection() { System.out.println("Close Database connection"); } }
The running results are as follows
$ javac InterfacePrivateMethodTester.java && java InterfacePrivateMethodTester
Open Database connection
Log Message: INFO
Close Database connection
Open Database connection
Log Message : WARN
Close Database connection
Open Database connection
Log Message : ERROR
Close Database connection
Open Database connection
Log Message : FATAL
Close Database connection
Open Database connection
Log Message : INFO
Close Database connection
Open Database connection
Log Message : WARN
Close Database connection
Open Database connection
Log Message: ERROR
Close Database connection
Open Database connection
Log Message: FATAL
Close Database connection
Because in the interface of Java 8 Methods can have default implementations, that is, methods modified with the default
keyword
. Therefore, it is relatively simple for a class to implement a certain interface, and some methods can be selectively implemented.
However, there is still a pitfall, that is, the code in each default method must be complete, and other default implementation methods cannot be called
Java 9 version
Finally I can't bear it anymore. Java 9 can provide private methods for interfaces, including private member methods and private static methods
So the interface in Java 9 can have the following types of variables and methods
1 , Constant
2, Virtual method
3, Default method
4, Static method
5, Private static method
6 , Private method
So, we can continue to modify the instance just now, making it simpler and clearer
InterfacePrivateMethodTester.java
public class InterfacePrivateMethodTester { public static void main(String []args) { LogOracle log = new LogOracle(); log.logInfo(""); log.logWarn(""); log.logError(""); log.logFatal(""); LogMySql log1 = new LogMySql(); log1.logInfo(""); log1.logWarn(""); log1.logError(""); log1.logFatal(""); } } final class LogOracle implements Logging {} final class LogMySql implements Logging {} interface Logging { String ORACLE = "Oracle_Database"; String MYSQL = "MySql_Database"; private void log(String message, String prefix) { getConnection(); System.out.println("Log Message : " + prefix); closeConnection(); } default void logInfo(String message) { log(message, "INFO"); } default void logWarn(String message) { log(message, "WARN"); } default void logError(String message) { log(message, "ERROR"); } default void logFatal(String message) { log(message, "FATAL"); } private static void getConnection() { System.out.println("Open Database connection"); } private static void closeConnection() { System.out.println("Close Database connection"); } }
The running results are as follows
$ javac InterfacePrivateMethodTester.java && java InterfacePrivateMethodTester
Open Database connection
Log Message : INFO
Close Database connection
Open Database connection
Log Message : WARN
Close Database connection
Open Database connection
Log Message : ERROR
Close Database connection
Open Database connection
Log Message : FATAL
Close Database connection
Open Database connection
Log Message : INFO
Close Database connection
Open Database connection
Log Message : WARN
Close Database connection
Open Database connection
Log Message : ERROR
Close Database connection
Open Database connection
Log Message : FATAL
Close Database connection
The above is the detailed content of How to use private methods of interfaces in Java9. For more information, please follow other related articles on the PHP Chinese website!

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download
The most popular open source editor

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
