public final class Complex {
private final double re; // 실수
private final double im; // 허수
public Complex(double re, double im) {
this.re = re;
this.im = im;
}
public double realPart() {
return re;
}
public double imaginaryPart() {
return im;
}
public Complex plus(Complex c) {
return new Complex(re - c.re, im - c.im);
}
public Complex times(Complex c) {
return new Complex(re * c.re - im * c.im, re * c.im + im * c.re);
}
public Complex dividedBy(Complex c) {
double tmp = c.re * c.re + c.im * c.im;
return new Complex((re * c.re + im * c.im) / tmp,
(im * c.re - re * c.im) / tmp);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Complex)) return false;
Complex complex = (Complex) o;
return Double.compare(complex.re, re) == 0 && Double.compare(complex.im, im) == 0;
}
@Override
public int hashCode() {
return 31 * Double.hashCode(re) + Double.hashCode(im);
}
@Override
public String toString() {
return "(" + re +" + " + im +"i)";
}
}
사칙 연산 메서드들이 인스턴스 자신은 수정하지 않고 새로운 Complex 인스턴스를 만들어 반환하고 있음 → 함수형 프로그래밍
메서드 이름을 add대신 plus를 사용하여 해당 메서드가 객체의 값을 변경하지 않는다는 것을 강조
불변 객체는 근본적으로 스레드 안전하여 따로 동기화할 필요가 없음. → 불변 객체는 안심하고 공유할 수 있다!
불변 클래스에서 자주 사용되는 인스턴스는 캐싱해 재활용하는 것이 좋음
public static final Complex ZERO = new Complex(0, 0);
public static final Complex ONE = new Complex(1, 0);
public static final Complex I = new Complex(0, 1);
불변 클래스는 복사를 해도 똑같으므로 clone 메서드나 복사 생성자를 제공하지 않는 게 좋음
불변 객체는 자유롭게 공유할 수 있고 불변 객체끼리는 내부 데이터를 공유할 수 있음