Inheritance in Design – How to Implement RealNumber and ComplexNumber Inheritance

designinheritance

Hopefully not too academic…

Let's say I need real and complex numbers in my SW library.

Based on is-a (or here) relationship, real number is a complex number, where b in imaginary part of complex number is simply 0.

On the other hand, my implementation would be, that child extends parent, so in parent RealNumber I'd have real part and child ComplexNumber would add imaginary art.

Also there is an opinion, that inheritance is evil.

I recall like yesterday, when I was learning OOP at university, my professor said, this is not a good example of inheritance as absolute value of those two is calculated differently (but for that we have method overloading/polymorfism, right?)…

My experience is, that we often use inheritance to solve DRY, as a result we have often artificial abstract classes in hierarchy (we often have problem to find names for as they do not represent objects from a real world).

Best Answer

Even if in a mathematical sense, a real number is a complex number, it is not a good idea to derive real from complex. It violates the Liskov Substitution Principle saying (among other things) that a derived class should not hide properties of a base class.

In this case a real number would have to hide the imaginary part of the complex number. It is clear that it makes no sense to store a hidden floating point number (imaginary part) if you only need the real part.

This is basically the same issue as the rectangle/square example mentioned in a comment.

Related Topic