In this lab, you will create a programmer-defined class and then use it in a Java program. The program should create two Rectangle objects and find their area and perimeter.InstructionsMake sure the class file named Rectangle.java is open.In the Rectangle class, create two private attributes named length and width. Both length and width should be data type double.Write public set methods to set the values for length and width.Write public get methods to retrieve the values for length and width.Write a public calculateArea() method and a public calculatePerimeter() method to calculate and return the area of the rectangle and the perimeter of the rectangle.Open the file named MyRectangleClassProgram.java.In the MyRectangleClassProgram class, create two Rectangle objects named rectangle1 and rectangle2.Set the length of rectangle1 to 10.0 and the width to 5.0. Set the length of ectangle2 to 7.0 and the width to 3.0.

Respuesta :

Answer:

class Rectangle{

//private attributes of length and width

private double givenLength;

private double givenWidth;

// constructor to initialize the length and width

public Rectangle(double length, double width){

 givenLength = length;

 givenWidth = width;

}

// setter method to set the givenlength

public void setGivenLength(double length){

 givenLength = length;

}

// setter method to set the givenWidth

public void setGivenWidth(double width){

 givenWidth = width;

}

// getter method to return the givenLength

public double getGivenLength(){

 return givenLength;

}

// getter method to return the givenWidth

public double getGivenWidth(){

 return givenWidth;

}

// method to calculate area of rectangle using A = L * B

public void calculateArea(){

 System.out.println("The area of the rectangle is: " + getGivenLength() * getGivenWidth());

}

// method to calculate perimeter of rectangle using P = 2 * (L + B)

public void calculatePerimeter(){

 System.out.println("The perimeter of the rectangle is: " + 2 * (getGivenLength() + getGivenWidth()));

}

}

public class MyRectangleClassProgram{

public static void main(String args[]){

//rectangle1 object is created

Rectangle rectangle1 = new Rectangle(10.0, 5.0);

//rectangle2 object is created

Rectangle rectangle2 = new Rectangle(7.0, 3.0);

//area for rectangle1 is calculated

rectangle1.calculateArea();

//perimeter for rectangle1 is calculated

rectangle1.calculatePerimeter();

//area for rectangle2 is calculated

rectangle2.calculateArea();

//perimeter for rectangle2 is calculated

rectangle2.calculatePerimeter();

}

}

Explanation:

Two file is attached: Rectangle.java and MyRectangleClassProgram.java

Ver imagen ibnahmadbello
Ver imagen ibnahmadbello
ACCESS MORE