Home > Java > javaTutorial > How to use java default method sqrt

How to use java default method sqrt

王林
Release: 2023-05-13 17:43:12
forward
1501 people have browsed it

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);
    }
}
Copy after login

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
Copy after login

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.

What collection classes are there in Java?

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template