java default method sqrt instance usage

  • 2021-09-05 00:13:21
  • OfStack

There are many methods that we can implement in the interface, among which the default method has attracted everyone's attention. Every time you want to implement a class and don't know where to start, besides using abstract methods, the default method sqrt is also a good choice. Let's briefly introduce one of these methods, and then bring the specific default method sqrt. Before that, let's have a brief understanding of other methods.

1. Java 8 allows us to use the default keyword to add non-abstract method implementations to interface declarations. This feature is also called an extension method. Here's our first example:


interface Formula {
  double calculate(int a);
  default double sqrt(int a) {
    return Math.sqrt(a);
  }
}

2. In the interface Formula, besides the abstract method caculate, a default method sqrt is defined. The Formula implementation class 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 as an anonymous object. The code is very wordy: It took 6 lines of code to realize a simple calculation function: a*100 square root.

Instance extension:


public class Test{ 
  public static void main(String args[]){
    double x = 11.635;
    double y = 2.76;

    System.out.printf("e  The value of is  %.4f%n", Math.E);
    System.out.printf("sqrt(%.3f)  For  %.3f%n", x, Math.sqrt(x));
  }
}

Compile the above program, and the output result is:

The value of e is 2.7183
sqrt (11.635) was 3.411


Related articles: