Bài tập java oop: tạo các setter, getter, constructor cho lớp Rectangle | Codelearn

  • TuanLQ7
  • Easy
  • 100 Points

Task

Create a Rectangle class with the following information:

Explanation:

  • length and width are the attributes that describe the length and width of a rectangle.
  • Rectangle() is the no-arg constructor.
  • Rectangle(length: double, width: double) is the constructor parameter used to initialize values to length and width.
  • setLength(length: double), getLength(), setWidth(width: double), getWidth()are setter and getter.
  • getArea() method returns the area of a rectangle.
  • getPerimeter() method returns the perimater of a rectangle.

A program to test the above Rectangle class:

public class Entry {
	public static void main(String[] args) {
		Rectangle r = new Rectangle(4, 5);
		System.out.println("Area: " + r.getArea());
		System.out.println("Perimeter: " + r.getPerimeter());
		r.setLength(2);
		r.setWidth(3);
		System.out.println("Area: " + r.getArea());
		System.out.println("Perimeter: " + r.getPerimeter());
	}
}

When the above code is compiled and executed, it produces the following result:

Area: 20.0
Perimeter: 18.0
Area: 6.0
Perimeter: 10.0

Instruction

You need to create a Rectangle class as below:

class Rectangle {
	private double length;
	private double width;

	public Rectangle() {

	}

	public Rectangle(double length, double width) {
		this.length = length;
		this.width = width;
	}

	public double getLength() {
		return length;
	}

	public void setLength(double length) {
		this.length = length;
	}

	public double getWidth() {
		return width;
	}

	public void setWidth(double width) {
		this.width = width;
	}

	public double getArea() {
		return length * width;
	}

	public double getPerimeter() {
		return (length + width) * 2;
	}
}