Home >Java >javaTutorial >How to implement virtual extension method in java
1. Java8 allows specific methods to be implemented in the interface, just add the default keyword before the method. This feature is also called virtual extension method.
interface Formual { double calculate(int a); default double sqrt(i nt a) { return Math.sqrt(a); } }
2. The Formual interface defines a default method sqrt. As long as the calculate method needs to be implemented, the sqrt method can be used out of the box.
Formula formula = new Formula() { @Override public double calculate(int a) { return sqrt(a * 100); } }; formula.calculate(100); // 100.0 formula.sqrt(16); // 4.0
The above is the detailed content of How to implement virtual extension method in java. For more information, please follow other related articles on the PHP Chinese website!