类中包括四种成员:成员变量、getter和setter、构造方法及方 法。 对成员变量进行保护,对传入数据进行检验,如数据不在 正确范围内,抛出异常信息;构造方法分无参、有参两种 设计复数类Complex,计算两个复数之和、差,同时以 a+bi 的字符串形式显示。使用复数类Complex,验证两个复数 1+2i 和3+4i 相加产生一个新的复数 4+6i ,相减产生一个新的复数 2 2i。
时间: 2023-11-22 21:53:00 浏览: 95
Java类-java_类基础
下面是一个复数类Complex的示例代码,包括成员变量、getter和setter、构造方法及方法:
```java
public class Complex {
private double real; // 复数的实部
private double imaginary; // 复数的虚部
public Complex() {
this.real = 0;
this.imaginary = 0;
}
public Complex(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
public double getReal() {
return real;
}
public void setReal(double real) {
this.real = real;
}
public double getImaginary() {
return imaginary;
}
public void setImaginary(double imaginary) {
this.imaginary = imaginary;
}
// 计算两个复数之和
public Complex add(Complex other) {
double sumReal = this.real + other.real;
double sumImaginary = this.imaginary + other.imaginary;
return new Complex(sumReal, sumImaginary);
}
// 计算两个复数之差
public Complex subtract(Complex other) {
double diffReal = this.real - other.real;
double diffImaginary = this.imaginary - other.imaginary;
return new Complex(diffReal, diffImaginary);
}
// 以 a+bi 的字符串形式显示复数
public String toString() {
String sign = (this.imaginary >= 0) ? "+" : "-";
return this.real + sign + Math.abs(this.imaginary) + "i";
}
}
```
使用方法如下:
```java
Complex c1 = new Complex(1, 2);
Complex c2 = new Complex(3, 4);
Complex sum = c1.add(c2);
Complex diff = c1.subtract(c2);
System.out.println("Sum: " + sum.toString()); // 输出 "Sum: 4+6i"
System.out.println("Difference: " + diff.toString()); // 输出 "Difference: -2-2i"
```
阅读全文