【发布时间】:2015-01-07 10:12:20
【问题描述】:
我无法理解类和构造函数的工作方式。 (这是在java中) 我必须创建一个名为 Complex 的类来操作复数,并且该类将有变量 realPart 和 ImaginaryPart 类型为 double。现在如果 c1 和 c2 是 Complex 类型的对象,那么如果我执行 c1.add(c2) 它应该返回 Complex 对象,它是两个对象的总和。但是这是我卡在我不知道如何添加这两个数字的部分?
到目前为止,我已经这样做了:
public static void main(String[] args) {
Complex c1 = new Complex(2, 8);
Complex c2 = new Complex(2.3, 5.4);
Complex c3 = c1.add(c2);
Complex c4 = Complex.add(c1,c2);
}
}
类复杂{
private double realPart;
private double imaginaryPart;
public Complex() {
}
public Complex(double c1, double c2) {
realPart = c1;
imaginaryPart = c2;
}
public void setValue(int numberOne) {
realPart = numberOne;
}
public Complex add(Complex other) {
Complex result = new Complex();
this.realPart = 3;
return result;
}
public Complex subtract(Complex other) {
Complex result = new Complex();
this.realPart = 5;
return result;
}
public String toString() {
return c1.add(c2);
}
}
【问题讨论】:
标签: java class object methods constructor