[Math] set theory subsets and inheirtance in Java

computer scienceelementary-set-theory

I started reading Concepts of Modern Mathematics and naturally, I came across set theory. I was wondering if someone could clarify my understanding for subsets by way of inheritance in Java or any other language.

If I say that $\mathbb K \subset \mathbb R$ and $\mathbb K$ is some set then would that be the same thing as saying that class A extends B within the context of Java code? Or in other words, $\mathbb K$ inherits the properties of $\mathbb R$ and furthermore, becomes the "child" of $\mathbb R$ or the $\subset$ (subset) of $\mathbb R$?

Would I be correct in my analogy?

Thanks

Best Answer

The inheritance hierarchy is a bad model for sets and subsets. The main problem is that subsets deal only with single relation, which is containment $\subset$, where inheritance has a two roles:

  • subtyping polymorphism,
  • modeling abilities of objects.

Consider the infamous example of squares and rectangles. In math, of course, the set of all squares is a subset of all rectangles. This may lead to an impression that square should be a subclass of the rectangle (as, the most general Object class it at the very top of the hierarchy). However, this is wrong, because square does not have all the abilities that rectangle has (e.g. having sides of different lengths). However, the other direction, that is the rectangle is a subclass of the square, also has drawbacks, e.g. one could imagine such code

double squareArea(Square s) {
  return s.side*s.side;
}

which is clearly wrong if the square is a superclass of the rectangle. Some think that this code is wrong, other that it makes the OP paradigm broken, and those forced to use OP frequently use the ad-hoc solution (naturally, there are exceptions) being that the abilities-modeling is more important (to the point that the author of the original Java class hierarchy admits he did it wrong, unfortunately I could not find the citation, so take it with a pinch of salt). One way or another (I don't want to start another Xmas vs. Easter discussion), inheritance is a not a good example of sets and subsets.

If you have to go with Java, there is an interface java.util.Set which would be more helpful that inheritance hierarchy. Indeed, $A \subset B$ if and only if for all $x \in A$ we have $x \in B$, or in java terms

boolean subset(Collection<?> a, Collection<?> b) {
  for (Object elem : b)
    if (!a.contains(b)) 
      return false;
  return true;
}

Just try of interpreting what are you reading in terms of collections, as those were designed to model sets, multisets, sequences, and so on.

I hope I didn't confuse you ;-)

Related Question