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

Implement a subclass Square that extends the Rectangle class. In the constructor

ID: 3674894 • Letter: I

Question

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. Question was posted but did not output anything. Use Java and make the program as simple as possible.

Explanation / Answer

I have written the code fro the square class. Working java code:

import java.util.Scanner;


public class Square extends Rectangle
{


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)
   {
Scanner sc_x = new Scanner(System.in);
Scanner sc_y = new Scanner(System.in);
Scanner sc_l = new Scanner(System.in);


System.out.println("Enter x:");
String x1 = sc_x.nextLine();
System.out.println("Enter y:");
String y1 = sc_y.nextLine();
System.out.println("Enter length:");
String l1 = sc_l.nextLine();

int x = Integer.parseInt(x1);
int y = Integer.parseInt(y1);
int length = Integer.parseInt(l1);

Square sq = new Square(x, y, length);
System.out.println(sq.toString());

   }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote