Home >Java >javaTutorial >How to use java default method sqrt
1. Java 8 allows us to use the default keyword to add non-abstract method implementations to interface declarations. This feature is also known as extension method. The following is our first example:
interface Formula { double calculate(int a); default double sqrt(int a) { return Math.sqrt(a); } }
2. In the interface Formula, in addition to the abstract method caculate, a default method sqrt is also defined. The implementation class of Formula only needs to implement the abstract method caculate. The default method sqrt can be used directly.
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 formula object implements the Formula interface in the form of an anonymous object. The code is very verbose: it took 6 lines of code to implement a simple calculation function: the square root of a*100.
Collections in Java are mainly divided into four categories:
1. List: ordered, repeatable;
2. Queue: ordered and repeatable;
3. Set: non-repeatable;
4. Map: unordered, with unique keys and non-unique values.
The above is the detailed content of How to use java default method sqrt. For more information, please follow other related articles on the PHP Chinese website!