In: Computer Science
Question 3: Write the following Java program.
A. Create a class called Quadrilateral that contains the following: [4 Marks]
• Five double type data fields for: side1, side2, side3, side4, and perimeter
• A no-argument constructor that creates a Quadrilateral with all sides equal to 1
• Methods named setSide1(double s1), setSide2(double s2), setSide3(double s3), and
setSide4(double s4) to set the values of the four sides
• A method named calculatePerimeter( ) to calculate and return the perimeter of the
quadrilateral
B. Create a child class called Square that contains a method named calculateArea() to
calculate the area of the Square. [2 Marks]
C. Create a java main class named TestQuad to do the following: [4 Marks]
• Create a Quadrilateral object named Quad1 and a Square object named Sq1.
• Call the methods setSide1(double s1), setSide2(double s2), setSide3(double s3), and
setSide4(double s4) to:
o set the sides of Quad1 to 10, 20, 25, and 30, respectively
o set all sides of Sq1 to 3
• Display the perimeter of Quad1 by calling the method calculatePerimeter ( ). Display
the perimeter of Sq1 by calling the method calculatePerimeter ( ).
• Display the area of Sq1 by calling the method calculateArea()
Hint: Perimeter = sum of all sides & Area of Square = side * side
Java code pasted below.
//class Quadrilateral
class Quadrilateral{
double side1,side2,side3,side4,perimeter;
//no-argument constructor
Quadrilateral()
{
this.side1=1;
this.side2=1;
this.side3=1;
this.side4=1;
}
//methods to set values for sides
void setSide1(double side1)
{
this.side1=side1;
}
void setSide2(double side2)
{
this.side2=side2;
}
void setSide3(double side3)
{
this.side3=side3;
}
void setSide4(double side4)
{
this.side4=side4;
}
double calculatePerimeter()
{
return side1+side2+side3+side4;
}
}
//class Square
class Square extends Quadrilateral{
double calculateArea()
{
return side1*side1;
}
}
//Main class
class TestQuad{
public static void main(String args[])
{
//creating the object of quadrilateral
Quadrilateral Quad1=new Quadrilateral();
//creating the object of square
Square Sq1=new Square();
//set the sides of Quadrilateral
Quad1.setSide1(10);
Quad1.setSide2(20);
Quad1.setSide3(25);
Quad1.setSide4(30);
//set the all sides of square to 0
Sq1.setSide1(3);
Sq1.setSide2(3);
Sq1.setSide3(3);
Sq1.setSide4(3);
//Display the perimeter of quadrilateral
double perimeter;
System.out.println("Perimeter of
Quadrilateral="+Quad1.calculatePerimeter());
//Display the perimeter of square
System.out.println("Perimeter of
Square="+Sq1.calculatePerimeter());
//calculate the area of square
double area;
System.out.println("Area of Square="+Sq1.calculateArea());
}
}
Output Screen