Implement a subclass Square that extends the Rectangle class. In the constructor
ID: 3673791 • 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.
Explanation / Answer
Can help u with this:
public class square
{
public static void main(String[] args)
{
Square sq = new Square(10, 20, 30);
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");
}
}
import java.awt.Rectangle;
public class Square extends Rectangle
{
public Squares22(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+ "]";
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.