找不到合适的构造函数(Java)

时间:2015-12-09 00:24:16

标签: java methods

我正在尝试编译我的程序,但是我遇到了一个小错误,错误是#34;没有为ComplexNumber找到合适的构造函数(double)。"到目前为止,这是我的代码。

public class ComplexNumber extends ImaginaryNumber
{
    private double realCoefficient;

    public ComplexNumber ( )
    {
        super ( );
        this.realCoefficient = 1;
    }

    public ComplexNumber (double r, double i)
    {
        super (i);
        this.realCoefficient = r;
    }

    public ComplexNumber add (ComplexNumber another)
    {
        return new ComplexNumber (this.realCoefficient + another.realCoefficient); //the error at complile occurs here, right at new.
    }//More Codes

我曾经遇到过这个问题,那是因为我没有参数化的构造函数。不过这一次,我确实有一个。所以这次我不知道这是什么问题。

这是我的ImaginaryNumber代码

public class ImaginaryNumber implements ImaginaryInterface
{
//Declaring a variable.
protected double coefficient;

//Default constructor.
public ImaginaryNumber( )
{
    this.coefficient = 1;
}

//Parameterized constructor.
public ImaginaryNumber(double number)
{
    this.coefficient = number;
}

//Adding and returing an imaginary number.
public ImaginaryNumber add (ImaginaryNumber another)
{
    return new ImaginaryNumber(this.coefficient + another.coefficient);
}//More Codes

我的ImaginaryNumber类工作正常。

2 个答案:

答案 0 :(得分:2)

Java正在寻找一个只有的构造函数:

public ComplexNumber(double d){
   //to-do
}

您需要创建一个适合这些参数的构造函数。

答案 1 :(得分:2)

add方法中,您试图将一个参数传递给构造函数,但只有构造函数需要0或2个参数。

看起来你需要添加ComplexNumber的虚部,所以将虚构部分加入作为构造函数的第二个参数。

使用coefficient中的Imaginary受保护变量:

return new ComplexNumber (this.realCoefficient + another.realCoefficient,
                          this.coefficient + another.coefficient);