设计一个复数类Complex,并在该类中实现将对象自身保存到文件的功能,实例方法void save(String fileName);从文件恢复数据的静态方法static Complex load(String fileName)
时间: 2024-03-23 11:41:58 浏览: 84
好的,我可以帮你设计一个Java的复数类Complex,并在该类中实现将对象自身保存到文件的功能,并实现从文件恢复数据的静态方法。下面是代码实现:
```java
import java.io.*;
public class Complex implements Serializable {
private double real;
private double imag;
public Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
public void save(String fileName) {
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(fileName));
out.writeObject(this);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static Complex load(String fileName) {
Complex c = null;
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));
c = (Complex)in.readObject();
in.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return c;
}
public double getReal() {
return real;
}
public double getImag() {
return imag;
}
public void setReal(double real) {
this.real = real;
}
public void setImag(double imag) {
this.imag = imag;
}
public Complex add(Complex other) {
double r = this.real + other.real;
double i = this.imag + other.imag;
return new Complex(r, i);
}
public Complex subtract(Complex other) {
double r = this.real - other.real;
double i = this.imag - other.imag;
return new Complex(r, i);
}
public Complex multiply(Complex other) {
double r = this.real * other.real - this.imag * other.imag;
double i = this.real * other.imag + this.imag * other.real;
return new Complex(r, i);
}
public Complex divide(Complex other) {
double r = (this.real * other.real + this.imag * other.imag) / (other.real * other.real + other.imag * other.imag);
double i = (this.imag * other.real - this.real * other.imag) / (other.real * other.real + other.imag * other.imag);
return new Complex(r, i);
}
public String toString() {
return "(" + real + ", " + imag + "i)";
}
}
```
在该类中,我们使用ObjectOutputStream和ObjectInputStream来实现将对象自身保存到文件的功能,以及从文件恢复数据的静态方法。注意,在实现这两个方法时,我们需要让Complex类实现Serializable接口。
使用示例:
```java
public static void main(String[] args) {
Complex c1 = new Complex(1, 2);
c1.save("complex.dat");
Complex c2 = Complex.load("complex.dat");
System.out.println(c2);
}
```
执行该程序,输出结果为:
```
(1.0, 2.0i)
```
阅读全文