Open Eclipse and create a Java project named Lab01. 2. Create a class Rectangle
ID: 3831851 • Letter: O
Question
Open Eclipse and create a Java project named Lab01. 2. Create a class Rectangle and declare the instance variables (data fields). 3. Create the class constructors. 4. Create the getter methods. Checkpoint: At this point you can check if the constructor and the getter methods work correctly. In the main method of the class create one object of type Rectangle, and then print the result of calling its getter methods. Run the program to see if the result is correct. 5. Create the setter methods. 6. Create methods for calculating a rectangle’s area and perimeter. 7. Create a toString() method. Checkpoint: In the main method of the class call the toString() method. Run the program to see if the result is correct. 8. Create a new client class TestRectangle. 9. In this class, create two objects of type Rectangle. 10. Calculate the area and perimeter for the two created rectangles. 11. Print the information for each rectangle by calling the method toString(), followed by the area and the perimeter of the rectangle. Checkpoint: Test the whole program. 12. Format properly your code. Add/complete comments. 13. Submit the two Java files Rectangle.java and TestRectangle.java to Blackboard.
Explanation / Answer
TestRectangle.java
public class TestRectangle {
public static void main(String[] args) {
Rectangles = new Rectangle(10, 20);
System.out.println(s);
System.out.println("The area of the rectangle of length 10.0 and width 20.0 is "+s.area());
System.out.println("The perimeter of the rectangle of length 10.0 and width 20.0 is "+s.perimeter());
Rectangles1 = new Rectangle(100, 200);
System.out.println(s1);
System.out.println("The area of the rectangle of length 100.0 and width 200.0 is "+s1.area());
System.out.println("The perimeter of the rectangle of length 100.0 and width 200.0 is "+s1.perimeter());
}
}
Rectangle.java
public class Rectangle{
private double width;
private double length ;
public Rectangle(double width, double length ){
this.width = width;
this.length = length ;
}
public Rectangle(){
}
public double area(){
return width * length;
}
public double perimeter(){
return 2 * width + 2 * length;
}
@Override
public String toString() {
return "Rectangle[length=" + length + ", width=" + width + "]";
}
}
output:
Rectangle[length=20.0, width=10.0]
The area of the rectangle of length 10.0 and width 20.0 is 200.0
The perimeter of the rectangle of length 10.0 and width 20.0 is 60.0
Rectangle[length=200.0, width=100.0]
The area of the rectangle of length 100.0 and width 200.0 is 20000.0
The perimeter of the rectangle of length 100.0 and width 200.0 is 600.0
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.