# Representing the hierarchy of groups of numbers using type inheritance

I've run into an interesting conundrum while coding my own implementations for the basic sets of mathematical numbers (Natural, Integer, Rational, Irrational, Real, Complex). I'm doing this mostly for fun, but also because I want properly represented numbers in code.

It started off with RationalNumber. I added two fields to my class: Numerator and Denominator. I've overloaded all the basic operators that I am able to (I'm using C#) so that I can define what it means to add, subtract, etc.. for these objects.

From here, I thought that I'd extend my definitions upward and make a `RealNumber` class such that this type can extend from it so that it could fill in for any RealNumber elsewhere in code... Except intuitively, the number system operates contrary to this definition.

Illustrating what I mean, consider starting off with the basic natural numbers. We can "extend" the natural numbers to include negative numbers as well (and zero if you weren't already including it) and then we call this new group the integers. In code, this would imply that `Integer` inherits from `NaturalNumber`. If I wanted to write a method that accepts an integer parameter, logically one would assume you could use a natural number as well; but with the way inheritance works, this doesn't fly.

How can I properly model the relationship between the sets of numbers through inheritance so that I can put a natural number into?

• Have you looked at it the other way around? Say, making `NaturalNumber` extend `Integer` instead. – cbojar Aug 3 '14 at 23:50
• That's what I wanted to do, and I could make it work, but it just seemed backwards from how I understood the relationship between the sets. I was thinking about it from an object oriented perspective where subclasses extended the superclass. – Mirrana Aug 4 '14 at 0:03
• You can think of extension as a "kind of" relationship. A dog is a kind of animal, so dog extends animal. In the same way `NaturalNumber` is a kind of `Integer`. – cbojar Aug 4 '14 at 0:18
• I would keep in mind square-rectangle (aka circle-ellipse) problem – gnat Aug 4 '14 at 8:29
• – gnat Apr 22 '16 at 12:31