Java 8 Default Methods
Java 8 introduced default methods for interfaces.
Simply put, default methods mean that interfaces can have implemented methods, and implementing classes do not need to implement them.
We just need to add the default keyword before the method name to implement a default method.
Why have this feature?
First, the previous interface was a double-edged sword. The advantage is that it is oriented towards abstraction rather than specific programming. The disadvantage is that when the interface needs to be modified, all classes implementing that interface must be modified. The current collection framework before Java 8 did not have a foreach method. The usual solution that can be thought of is to add new methods and implementations to the relevant interfaces in the JDK. However, for already released versions, there is no way to add new methods to an interface without affecting existing implementations. So default methods were introduced. Their purpose is to solve the incompatibility between interface modifications and existing implementations.
Syntax
The syntax format of a default method is as follows:
Multiple Default Methods
If an interface has a default method, consider the situation where a class implements multiple interfaces, and these interfaces have the same default method. The following example illustrates the solution to this situation:
The first solution is to create your own default method to override the default method of the interface:
The second solution is to use super to call the default method of the specified interface:
Static Default Methods
Another feature of Java 8 is that interfaces can declare (and provide implementations of) static methods. For example:
Default Method Example
We can understand the use of default methods through the following code. You can put the code in the Java8Tester.java file:
Java8Tester.java file
Executing the above script, the output result is:
$ javac Java8Tester.java $ java Java8Tester 我是一辆车! 我是一辆四轮车! 按喇叭!!! 我是一辆汽车!
Other Extensions
Java 8 New Features