For symbolic representation of mathematical expressions, I am trying to build a hierarchy of number system classes.
In addition to Integer
and Real
, I also need classes like Rational
and Complex
. I want all of these classes to inter-operate seamlessly with each other.
e.g. Adding a Complex
number to an Integer
would give a Complex
number etc.
I made all of them to implement the Number
interface. (NOT java.lang.Number
)
For being able to add numbers of different types, I tried making hierarchy like following.
Integer
extendsRational
extendsReal
extendsComplex
- This makes an
Integer
to unnecessarily store imaginary part etc. This overhead is undesired. - Also allowing access to imaginary part of an
Integer
seems improper.
Can anyone suggest a better design where overhead is avoided and interoperation is still possible?
I'd rather create an interface that has something like getRealPart() and getImaginaryPart(). Then your integer can simply return 0 for getImaginaryPart(). That since you want Integer to "be" a Complex, but you don't want Integer to contain the internal implementation of Complex.
I don't see a problem here. Real number is a complex number, integer is a real number. Complex number can be expressed as
a + bi
and an integer is a complex number, such thata
is an integer andb = 0
. So every integer hasb
and it is equal to 0.You may however consider using composition (and interfaces) over inheritance:
The disadvantage of this approach is that
Integer
class can overrideb()
method, so maybe inheritance would be better, because you can usefinal
keyword on the method:I have tried to model it myself and I came up with this terrible code below. I am not happy about it, because of the following problems:
Interface
-InterfaceImpl
antipatternIntegerNumber
has methods such asrealPart()
ornumerator()
anddenominator()
Code:
I am wondering whether interfaces should be abstract classes with implemented methods being final. In the end, I think it may be better to just go with simple inheritance and ignore the fact that every integer will have a field for imaginary part.
I hope this will give you some ideas.