java构造函数中的简单错误

mis*_*app 1 java

我无法理解我在这段代码中的错误,如果我写的话会编译,new Cosine();但如果写的话会失败new Cosine(x);

import java.lang.Object;
import java.lang.Math;

class Cosine {
    double Cosine (double x) {
    double result = Math.cos(Math.toRadians(x));
    return result;
  }
}

public class test {
     public static void main (String[] args){
     double x = 90;
     new Cosine(x);
  }
}   
Run Code Online (Sandbox Code Playgroud)

Pau*_*ora 6

你还没有给出Cosine一个构造函数double.试试这个:

class Cosine {

    public final double result; //field holding the result

    //constructor
    public Cosine (double x){
     result = Math.cos(Math.toRadians(x)); //compute the result
   }
}

public class test {
    public static void main (String[] args){
        double x = 90;
        double cosX = new Cosine(x).result;
    }
}
Run Code Online (Sandbox Code Playgroud)

虽然这提出了一个问题,为什么不能使用简单的静态方法:

public static double getCosine(double x) {
    return Math.cos(Math.toRadians(x));
}

public class test {
    public static void main (String[] args){
        double x = 90;
        double cosX = getCosine(x);
    }
}
Run Code Online (Sandbox Code Playgroud)

这不需要Cosine为每次计算实例化对象.