Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

P10.10 Implement a subclass Square that extends the Rectangle class. In the cons

ID: 3634553 • Letter: P

Question

P10.10
Implement a subclass Square that extends the Rectangle class. In the constructor,
accept the x- and y-positions of the center and the side length of the square. Call the
setLocation and setSize methods of the Rectangle class. Look up these methods in the
documentation for the Rectangle class. Also supply a method getArea that computes
and returns the area of the square. Write a sample program that asks for the center
and side length, then prints out the square (using the toString method that you
inherit from Rectangle) and the area of the square.

Explanation / Answer

if you have any queries regarding this coding or any changes let me know....

//Rectangle Class---Super Class


package com.cramster.rakesh;

public class Rectangle {

public int x,y,width,height;



public void setLocation(int x, int y) {
this.x = x;
this.y = y;
}

public void setSize(int width, int height) {

this.width = width;
this.height = height;
}

public String toString() {
int x = (int) getX();
int y = (int) getY();
int w = (int) getWidth();
int h = (int) getHeight();
return "Square[x=" + x + ",y=" + y + ",width=" + w + ",height=" + h + "]";
}


public int getX() {
return x;
}

public void setX(int x) {
this.x = x;
}

public int getY() {
return y;
}

public void setY(int y) {
this.y = y;
}

public int getWidth() {
return width;
}

public void setWidth(int width) {
this.width = width;
}

public int getHeight() {
return height;
}

public void setHeight(int height) {
this.height = height;
}
}




//Square Class(Subclass) extends Rectangle

package com.cramster.rakesh;

public class Square extends Rectangle{

//Constructor with three parameters

public Square(int x, int y, int length) {
setLocation(x - length / 2, y - length / 2);
setSize(length, length);
}

public int getArea() {
return (int) (getWidth() * getHeight());
}

public String toString() {
int x = (int) getX();
int y = (int) getY();
int w = (int) getWidth();
int h = (int) getHeight();
return "Square{x=" + x + ",y=" + y + ",width=" + w + ",height=" + h + "}";
}

public static void main(String[] args)
{
Square sq = new Square(28, 20, 28);
System.out.println(sq.toString());
//System.out.println("Expected: Square[x=-5,y=5,width=30,height=30]");
System.out.println("Area: " + sq.getArea());
//System.out.println("Expected: 900");
}


}



OutPut:----

Square{x=14,y=14,width=28,height=28}
Area: 784