Create an entire class called Square. Square contains one data member( a double)
ID: 3834558 • Letter: C
Question
Create an entire class called Square. Square contains one data member( a double) called side. in your class you will have 2 constructors(default one that sets side to 0,and one that sends in sides value as a parameter).Also you will need 1 accessor and 1 modifier for the variable. A instance method called the area of the square(area=side*side)Finally crest an instance method called add which allows us to add which allows us two two we are adding.Note it is not just adding the sides! write the code that create twoSqure objects using each of the two constructor and than adds them togethers to create a third
Explanation / Answer
/**
* Square class that set side of the square
* and finds area of square
* */
//Square.java
public class Square
{
//instance data member
private double side;
//default constructor
public Square() {
side=0;
}
//parameterized constructor
public Square(double side) {
setSide(side);
}
//Method to set side
public void setSide(double side){
this.side=side;
}
//Return side
public double getSide(){
return side;
}
//area of square
public double area(){
return side*side;
}
/*
* add method that takes a square object
* and add the two square sides
* and returns the square object.
* */
public Square add(Square square){
//add two sides of square and this square
double tempSide=this.side+square.getSide();
//return an instance of Square class
return new Square(tempSide);
}
}
------------------------------------------------------------------------------------------------------------------------------------------------------
/*
* The java class SquareDriver that tests
* the square class and set side and finds
* area and add two sides of squares and
* prints the area to console.
* */
//SquareDriver.java
public class SquareDriver {
public static void main(String[] args) {
//create two instances of Square class objects
Square square1=new Square();
square1.setSide(5);
Square square2=new Square();
square2.setSide(10);
System.out.println("Side1 of Square: "+square1.getSide());
System.out.println("Side2 of Square: "+square1.getSide());
Square resultSquare=square1.add(square2);
System.out.println("Side of result square : "+resultSquare.getSide());
System.out.println("Area of result square : "+resultSquare.area());
}
}
------------------------------------------------------------------------------------------------------------------------------------------------------
Sample run:
Side1 of Square: 5.0
Side2 of Square: 5.0
Side of result square : 15.0
Area of result square : 225.0
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.