无法理解类对象和构造函数

时间:2014-11-10 23:45:41

标签: java class object methods constructor

我无法理解类以及构造函数的工作方式。 (这是在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);

}

}

class Complex {

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);
}

}

3 个答案:

答案 0 :(得分:0)

像这样:

public Complex add(Complex other) {
    Complex result = new Complex();
    result.realPart = this.realPart + other.realPart;
    result.imaginaryPart = this.imaginaryPart + other.imaginaryPart;

    return result;
}

答案 1 :(得分:0)

首先在新Complex内计算出您想要的值,然后根据这些值使用new制作新的Complex。最后,使用return使您的新Complex方法调用返回的值。

这是实现它的一种方法,但不是唯一的方法。请注意,当您编写realPart而未指定要查找其实部的对象时,它将是当前对象中的realPart - 方法调用中点之前的那个。{1}}。换句话说,它与撰写this.realPart相同。

public Complex add(Complex other) {
    double realPartOfResult = realPart + other.realPart;
    double imaginaryPartOfResult = imaginaryPart + other.imaginaryPart;
    Complex result = new Complex(realPartOfResult, imaginaryPartOfResult);
    return result;
}

答案 2 :(得分:0)

例如,如果您执行:c1.Add(c2),则"this"将成为Complex对象c1

public Complex add(Complex other) {
    Complex result = new Complex();
    double realResult = this.realPart + other.realPart;
    double imaginaryResult = this.imaginaryPart + other.imaginaryPart;
    result.realPart = realResult;
    result.imaginaryPart = imaginaryResult;
    return result;
}

关于Substruct方法

的相同方式
public Complex subtract(Complex other) {
    Complex result = new Complex();
    double realResult = this.realPart - other.realPart;
    double imaginaryResult = this.imaginaryPart - other.imaginaryPart;
    result.realPart = realResult;
    result.imaginaryPart = imaginaryResult;
    return result;
}

我建议你阅读: https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html