Java中引用变量(引用)的默认构造函数

时间:2018-04-24 23:06:01

标签: java default-constructor

我在Java中有以下两个类,我可以使用它来计算复数的结果。

    class Calculator{
       private ComplexNumber compNum1;
       private ComplexNumber compNum2;

    public Calculator(){
        compNum1 = new ComplexNumber();
        compNum2 = new ComplexNumber();
    }

    public Calculator(ComplexNumber compNum1, ComplexNumber compNum2){
        this.compNum1 = compNum1;
        this.compNum2 = compNum2;
    }

    public ComplexNumber addTwoNumbers(){
        ComplexNumber sumOfTwoNumbers = new ComplexNumber();
        sumOfTwoNumbers.real = compNum1.real + compNum2.real;
        sumOfTwoNumbers.imaginary = compNum1.imaginary + compNum2.imaginary;
        return sumOfTwoNumbers;
    }

    public ComplexNumber subTwoNumbers(){
        ComplexNumber differenceOfTwoNumbers = new ComplexNumber();
        differenceOfTwoNumbers.real = compNum1.real - compNum2.real;
        differenceOfTwoNumbers.imaginary = compNum1.imaginary - compNum2.imaginary;
        return differenceOfTwoNumbers;
    }

    public ComplexNumber mulTwoNumbers(){
        ComplexNumber productOfTwoNumbers = new ComplexNumber();
        productOfTwoNumbers.real = (compNum1.real*compNum2.real) - (compNum1.imaginary*compNum2.imaginary);
        productOfTwoNumbers.imaginary = (compNum1.real*compNum2.imaginary) + (compNum1.imaginary*compNum2.real);
        return productOfTwoNumbers;
    }
}

class ComplexNumber{
    public double real;
    public double imaginary;

    public ComplexNumber(){
        real = 0.0;
        imaginary = 0.0;
    }

    public ComplexNumber(double real, double imaginary){
        this.real = real;
        this.imaginary = imaginary;
    }
}

我为 ComplexNumbers 类定义了一个默认构造函数,但对于计算器类,数据字段是引用,而不是原始数据类型甚至字符串,我应该声明计算器的默认构造函数,就像我在代码中所做的那样?

谢谢!

0 个答案:

没有答案