(In java, and please writes comment)Suppose we want to implement a drawing progr
ID: 3917480 • Letter: #
Question
(In java, and please writes comment)Suppose we want to implement a drawing program that creates various shapes using keyboard characters. Implement an abstract base class DrawableShape that know the center (two integer values) and the color (a string) of the object. Give appropriate accessor methods for the attributes. Also a mutator method that moves the object by a given amount.
Create a class Square derived from DrawableShape. A Square object should know the length of its sides. The class should have an accessor method and a mutator method for this length. It should also have methods for computing the area and perimeter of the square. Although characters are taller than they are wide - so the number of characters in the vertical sides will differ from the number in the horizontal sides, do not worry about this detail.
Create a test class that creates an array of 10 instances of Square and sort them.
Explanation / Answer
Java code:
DrawableShape class:
public abstract class DrawableShape
{
//attributes
private int x,y;
private String color;
//accessor methods for attributes
public int getX() {
return x;
}
public int getY() {
return y;
}
public String getColor() {
return color;
}
}
Square class:
public class Square extends DrawableShape
{
//attribute
private int length;
//accessor and mutator for attribute
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
//computes area of the square
public int computeArea()
{
return (int) Math.pow(length, 2);
}
//computes perimeter of the square
public int computePerimeter()
{
return 4*length;
}
}
Test class:
import java.util.Random;
public class TestClass {
public static void main(String[] args)
{
//array of 10 instances of Square
Square squares[] = new Square[10];
//random object to generate random numbers
Random rand = new Random();
for (int i = 0; i <= 9; i++)
{
Square ob = new Square();
/*Generate random integers in range 0 to 55
and setting the length of the Square by random integer*/
ob.setLength(rand.nextInt(50));
//Assigning Square object to squares array
squares[i] = ob;
}
//for loop to print computed area,and perimeter of the square
for(int i=0;i<10;i++)
{
System.out.println("Area:"+squares[i].computeArea()+" Perimeter:"+squares[i].computePerimeter());
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.