Answer to Question #299469 in Java | JSP | JSF for lolo

Question #299469

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-19T16:56:59-0500
class Square extends Rectangle {


	public Square(int side) {
		super(side, side);
		System.out.println("Square Constructor");
	}


	/***
	 * area - prints "Square Area" and returns the area of the Square
	 * 
	 * @return
	 */
	public int area() {
		System.out.println("Square Area");
		return this.getLength() * this.getWidth();
	}


	/**
	 * perimeter - prints "Square Perimeter" and returns the perimeter of the Square
	 * 
	 * @return
	 */
	public int perimeter() {
		System.out.println("Square Perimeter");
		return 2 * (this.getLength() + this.getWidth());
	}


	/**
	 * @param length the length to set
	 */
	public void setLength(int side) {
		super.setLength(side);
	}


	/**
	 * @param width the width to set
	 */
	public void setWidth(int side) {
		super.setWidth(side);
	}


	public String toString() {
		return "A Square with side="+this.getLength()+", 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