uetoyo
uetoyo

Reputation: 329

Class hierarchy of shapes

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.

Upvotes: 0

Views: 1491

Answers (4)

Jean-Pierre Schnyder
Jean-Pierre Schnyder

Reputation: 1944

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.

Upvotes: 0

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.

Upvotes: 1

Lukas Eichler
Lukas Eichler

Reputation: 5913

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

Upvotes: 1

arshajii
arshajii

Reputation: 129537

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.

Upvotes: 2

Related Questions