我正在尝试编写一个ComplexNumber类,它继承了我的ImaginaryNumber类中的数据和方法。所以在我的ImaginaryNumber类中我有这个
public class ImaginaryNumber
{
//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
在我的ComplexNumber课程中,我有这个
public class ComplexNumber extends ImaginaryNumber
{
private double realCoefficient;
public ComplexNumber ( )
{
super ( );
this.realCoefficient = 1;
}
public ComplexNumber (double realNum, double IM)
{
super (IM);
this.realCoefficient = realNum;
}
public ComplexNumber add (ComplexNumber a, ComplexNumber b)
{
return new ComplexNumber (this.realCoefficient + a.realCoefficient, super(b) + super(IM)); //I am confused on what to do here.
}//More Codes
我坚持的部分是加法。我不知道如何从我的ImaginaryNumber类调用该方法来处理Imaginary部分。我假设我必须以某种形式使用super()。但我不知道调用方法的正确语法。
也只是为了仔细检查。我是否正确地在我的ImaginaryNumber类中调用我的构造函数?
答案 0 :(得分:0)
我是这么认为的,通过这样做你想要添加复数的数字。所以在你的ImaginaryNumber类中,你必须有一个返回系数的方法。
public double getImaginaryCoefficient() {
return this.coefficient;
}
现在,您可以调用getImaginaryCoefficient()方法并执行您想要执行的任何操作。
像这样,
public ComplexNumber add (ComplexNumber a, ComplexNumber b)
{
return new ComplexNumber (this.realCoefficient + a.realCoefficient, a.getImaginaryCoefficient()+b.getImaginaryCoefficient()); //I am confused on what to do here.
}//More Codes