In: Computer Science
Create a Square Class and Create a graphical representation of your Square class
- your class will have the following data fields: double width, String color.
- provide a no-args constructor.
- provide a constructor that creates a square with the specific width
- implement method getArea()
- implement method getPerimeter()
- implement method setColor().
- draw a UML diagram for your class
- write a test program that will create a square with the width 30, 40 and 50.
Display the width, area and perimeter of each of your squares.
UML class diagram of Square class
//Square.java
class Square
{
double width;
String color;
//No args constructor
Square()
{
width=0.0;
color="black";
}
//constructor to assign width
Square(double w)
{
width=w;
}
// area=width*width
double getArea()
{
return width*width;
}
//perimeter=4*width
double getPerimeter()
{
return 4*width;
}
// to assign color
void setColor(String c)
{
color=c;
}
public String toString()
{
return "\nWidth = "+this.width+"\nArea ="+
this.getArea()+"\nPerimeter = "
+this.getPerimeter()+"\ncolor:"+this.color;
}
}
//Main.java
public class Main
{ public static void main(String[] args) {
Square sq1=new Square(30);
Square sq2=new Square(40);
Square sq3=new Square(50);
sq1.setColor("RED");
sq2.setColor("BLUE");
sq3.setColor("GREEN");
System.out.println("Square 1: ");
System.out.println(sq1);
System.out.println("Square 2: ");
System.out.println(sq2);
System.out.println("Square 3: ");
System.out.println(sq3);
}
}