Java 从另一个类设置参数

Java 从另一个类设置参数,java,Java,我想做的是对复数有不同的计算方法。我已经创建了有理数的所有计算,需要使用我以前使用的有理数类来创建复数。下面是我如何创建RationalPart不完整版本的 public class Rational { int numerator; int denominator; // Task 3: add the missing fields public Rational(int numerator, int denominator){ this.numerator = numerator;

我想做的是对复数有不同的计算方法。我已经创建了有理数的所有计算,需要使用我以前使用的有理数类来创建复数。下面是我如何创建RationalPart不完整版本的

public class Rational {
int numerator;
int denominator;
// Task 3: add the missing fields

public Rational(int numerator, int denominator){
    this.numerator = numerator;
    this.denominator = denominator;
    // Task 4: complete the constructor
}


public Rational add(Rational other){
    Rational result = new Rational(0,0);
    result.denominator = denominator * other.denominator;
    result.numerator = (numerator * other.denominator) + (denominator * other.numerator);
    return result;

}

......
......
......


public Rational divide(Rational other){
    Rational result = new Rational(0,0);
    result.denominator = denominator * other.numerator;
    result.numerator = numerator * other.denominator;
    return result;
    // Task 4: complete the method

}
现在我的任务是创建与此完全相同的东西,但只是在复数版本中。以下是我创建的内容:

public class Complex {
Rational real;
Rational imag;
// Task 6: add the missing fields


public Complex(Rational real, Rational imag){
    this.real = real;
    this.imag = imag;
    // Task 7: complete the constructor
}

public Complex add(Complex other){
    Complex result = new Complex(); ///Here is the problem!!!
    result.real = real.add(other.real);
    result.imag = imag.add(other.imag);
    return result;
    // Task 7: complete the method

}
当我想要创建新的复数来操作复数加法时,我不知道应该将什么作为参数,因为它必须基于rational类。任何帮助都将不胜感激。

为什么不呢

public Complex add(Complex other){
    Complex result = new Complex(other.real, other.imag);
    return result;
}

谢谢你的回复。但我仍然想知道如何在主要方法中利用这一点。当我像main方法中的一个例子那样创建时,比如说,3代表real部分,2i代表imagine部分,如果需要插入有理数格式,我如何创建一个新的复数?看看你的代码,你似乎必须先创建有理值,从中你可以创建复杂的对象。这就是我一直在努力的部分。如果我需要在复数类中创建有理值,我应该在类中还是在构造函数中创建它?对不起,不知道,为什么不试试看?你需要一个没有任何参数的构造函数。公共综合体