Class hierarchy of shapes

2013-06-30 java oop subclassing

Hello I have these classes in my Java exercise: Rectangle and Ellipse. Is Square child of Rectangle or should I make special constructor?

// constructor for Square
public Rectangle(double side) {
    this.width = side;
    this.height = side;
}

Is Circle child of Ellipse (extends)?

This could be a simple application like Kojo or Geogebra.

Answers

Yes, it seems reasonable to think of a Square as a subclass of Rectangle for which both the width and the height are equal:

public Square(double side) {
    super(side, side);  // reference to Rectangle constructor
}

Similarly, the same can be said for Circle, which is essentially an ellipse for which both the major and minor radii are equal:

public Circle(double radius) {
    super(radius, radius);  // reference to Ellipse constructor
}

Whether or not you want to create concrete subclasses to represent these shapes is up to you, and you should do whichever makes more sense in the context of your program.

The question here is: Do you create this hierachy to work with or just for the design sake?

If you are doing it for the design, create a class that extends from Rectangle otherwise it is just make your code more complex without any real improvements. You can apply the same to the Circle/Ellipse problem

Neither nor! Both should be subclasses of an abstract shape. You might want to do some coordinate transformations in this base class, so that subclasses can simply implement either an origin centered circle or square. But you don't want one of them to be the subclass of the other.

Why? Because you have to design for behaviour/interfaces, not for data! Designing for data almost invariably leads to convoluted designs in my experience.

And, unless you have specific reasons to actually provide circle/rectangle classes (see comments below), it does not seem like a good idea to have an extra class for a circle, given you already have an ellipse, that would just be redundant code. I would use specialized constructors to construct the more constrained cases.

Deriving a Square from a Rectangle or a Circle from an Ellipse both violate the Liskov substitution principle. See Is deriving square from rectangle a violation of Liskov's Substitution Principle? for the demonstration.

Related