Answer to Question #298711 in Java | JSP | JSF for Jackie

Question #298711

a) Write a class called Square, as a subclass of Rectangle. Convince yourself that Square can be modeled as a subclass of Rectangle. Square has no instance variable, but inherits the instance variables width and length from its superclass Rectangle.

· Provide the appropriate constructors (as shown in the class diagram). Hint:

public Square(double side) {

super(side, side); // Call superclass Rectangle(double, double)

}

· Override the toString() method to return "A Square with side=xxx, which is a subclass of yyy", where yyy is the output of the toString() method from the superclass.

· Do you need to override the getArea() and getPerimeter()? Try them out.

· Override the setLength() and setWidth() to change both the width and length, so as to maintain the square geometry.



1
Expert's answer
2022-02-16T14:54:53-0500
public class Square extends Rectangle {

    public Square(double side) {
        super(side, side);
    }

    @Override
    public void setLength(double length) {
        super.setWidth(length);
        super.setLength(length);
    }

    @Override
    public void setWidth(double width) {
        setLength(width);
    }

    @Override
    public String toString() {
        return "A Square with side=" + getWidth() + ", which is a subclass of " + super.toString();
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS