I have an abstract super class that implements an interface:
public abstract class FooMatrix implements Matrix {
public Vector multiply(Vector vec) {
// Code for Matrix * Vector
}
}
public interface Matrix {
public Vector multiply(Vector vec);
}
and then I have a subclass that extends the super class and implements a second interface that represents a mathematical subclass of the mathematical class represented by the first interface:
public interface Vector {
// Methods
}
public class FooVector extends FooMatrix implements Vector {
@Override
public Matrix multiply(Vector rightVec) {
// Code for Vector * Vector
}
}
So the subclass is returning a super class of the return type of the abstract super class. This isn’t working, and I want to know how I can make it work.
In mathematics, vectors are a subclass of matrices. A matrix times a matrix yields another matrix, in general. If the second matrix is a vector, the result is a vector. If both matrices are vectors, the result is a matrix or a scalar for column vector times row vector or row vector times column vector, respectively. This assumes the dimensions are compatible.
I would like to represent this behaviour with Java classes in a way that respects mathematics and gives the most specific return types possible. In other words, I want fooMatrix.multiply(Vector vec) to return Vector, and not just Matrix, but I want fooVector.multiply(Vector rightVec) to return Matrix and not Vector (which would be incorrect.) I can deal with a scalar as a 1×1 Matrix with another Vector method inner that calls multiply(Vector rightVec) and then returns the single element of the 1×1 return Matrix as a scalar.
I have found questions regarding covariant return types, but nothing like this.
Thanks!
Because
MatrixandVectorare in two different hierarchies. You cant useMatrixin place ofVectoras a return type.If you are not sure of the return type whether its going to be of type
MatrixorVector, you can new interface which is extended byMatrixandVectorand use it as return type.Somewhat like
change
Matrixtosame with Vector
If you use
MatrixOrVectoras return type, you can return object which is of typeMatrixorVector.Also just FYI
FooMatrixis not a abstract class because you are missingabstractthere. read more about abstract http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html