The Rectangle class in Java\'s AWT package does not include methods to compute i
ID: 3928180 • Letter: T
Question
The Rectangle class in Java's AWT package does not include methods to compute its area or the perimeter. Create a child class called BetterRectangle from the Rectangle class that has getPerimeter() and getArea() methods.You'll need to import the java.awt.Rectangle package to access Rectangle. Do not add any other variables or methods to the child class. In the constructor, take four parameters (int x, int y, int width, int height) and use the setLocation and setSize methods from the Rectangle class to set up BetterRectangle. Include a main method in your class that creates two objects and tests the methods you added. Hint: review the Java API documentation for Rectangle to see how to access information inside of it
Explanation / Answer
Hi, Please find my code.
Please let me know in case of any issue:
import java.awt.Rectangle;
public class BetterRectangle extends Rectangle {
// constructor
public BetterRectangle(int x, int y, int width, int height){
// calling setLocation
setLocation(x, y);
// calling setSize
setSize(width, height);
}
// method to return perimeter
public double getPerimeter(){
return 2*(getHeight() + getWidth());
}
// function to return area
public double getArea(){
return getHeight()*getWidth();
}
// main method
public static void main(String[] args) {
// Creating two objects of type BetterRectangle
BetterRectangle r1 = new BetterRectangle(3, 4, 6, 7);
BetterRectangle r2 = new BetterRectangle(5, 6, 12, 15);
System.out.println("R1: Area: "+r1.getArea()+", Perimeter: "+r1.getPerimeter());
System.out.println("R2: Area: "+r2.getArea()+", Perimeter: "+r2.getPerimeter());
}
}
/*
Sample Run:
R1: Area: 42.0, Perimeter: 26.0
R2: Area: 180.0, Perimeter: 54.0
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.