Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: weak pre condition and strong post condition, how to?

I'm having a really hard time in understanding how pre-conditions and post-conditions must work, without violate the Substitution Principle. So let's assume that we have a class Rectangle and Square—how to relate them? Which one must be the subclass?

So I undertand that the pre-conditions of a Subtype can be weaker, that means that we can take a major 'set' of things in out subclass, on the other hand the post-condition can be stronger so we can return a minor 'set' of things. How can I appply these rules in my example?

I read that the baseclass must 'do' less than the subclass, so I think that Square must be our baseclass and Rectangle the subclass. Thus the pre-condition in Square must be assert that height == width, but what about the post-conditions and the pre-conditions in Rectangle?

like image 964
Francesco Avatar asked Sep 14 '25 00:09

Francesco


1 Answers

A general way to find out super and subclasses, you basically need to answer this question:

Is every X a Y?

In you case you need to say these two things:

  • Is every Rectangle a Square? No.
  • Is every Square a Rectangle? Yes.

Thus Square is a Rectangle. Then the condition for becoming Square is:

  • If it's a rectangle; and
  • the height equals the width.
like image 147
nafas Avatar answered Sep 15 '25 14:09

nafas