Java의 유형 시스템은 단순히이를 표현할 수 없습니다. 여기에 해결 방법이 있습니다.
관심있는 수치 연산을 제공하는 인터페이스 Numeric
를 만들고 관심있는 데이터 형식의 구현을 작성합니다.
interface Numeric<N> {
public N add(N n1, N n2);
public N subtract(N n1, N n2);
// etc.
}
class IntNumeric extends Numeric<Integer> {
public static final Numeric<Integer> INSTANCE = new IntNumeric();
private IntNumeric() {
}
public Integer add(Integer a, Integer b) {
return a + b;
}
public Integer subtract(Integer a, Integer b) {
return a - b;
}
// etc.
}
을 그리고이 구현을 허용하도록 Matrix
클래스 생성자를 다시 작성.
class Matrix<N> {
private final Numeric<N> num;
private final List<List<N>> contents;
public Matrix(Numeric<N> num) {
this.num = num;
this.contents = /* Initialization code */;
}
public Matrix<N> add(Matrix<N> that) {
Matrix<N> out = new Matrix<N>(num);
for(...) {
for(...) {
out.contents.get(i).set(j,
num.add(
this.contents.get(i).get(j),
that.contents.get(i).get(j),
)
);
}
}
return out;
}
}
// Use site
Matrix<Integer> m = new Matrix<Integer>(IntNumeric.INSTANCE);
희망이 있습니다.
'Cat'은'Animal'을 확장하고,'Dog'는'Animal'의 서브 클래스입니다. 그렇다고해서 Cat이 예상되는 곳에 Dog를 반환 할 수있는 것은 아닙니다. –
@OliCharlesworth T에 캐스팅을 시도했지만 도움이되지 않았다. –
@ NuclearGhost : 어떤 오류가 있었습니까? – SLaks