Home > Java > javaTutorial > How to implement virtual extension method in java

How to implement virtual extension method in java

WBOY
Release: 2023-04-30 22:58:05
forward
827 people have browsed it

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

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

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!

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