用java编程语言实现

写一个名为Rectangle的类表示矩形。其属性包括宽width和高height颜色color,width和height都是double型的。要求该类具有:使用getter和setter的形式完成属性的访问及修改;提供计算面积的getArea()方法 。

初学者呀,死去的大二知识来了

public class Rectangle {
    private double width;
    private double height;
    private String color;

    public Rectangle(double width, double height, String color) {
        this.width = width;
        this.height = height;
        this.color = color;
    }

    public double getWidth() {
        return width;
    }

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

    public double getHeight() {
        return height;
    }

    public void setHeight(double height) {
        this.height = height;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

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

上述代码定义了一个Rectangle类,具有三个属性:width、height和color,分别表示矩形的宽、高和颜色;还有一个构造方法、六个访问和修改属性的getter和setter方法,以及一个计算矩形面积的getArea()方法。

使用时可以先实例化一个Rectangle对象,然后通过getter和setter方法访问和修改其属性,最后调用getArea()方法计算矩形面积。例如:
Rectangle rect = new Rectangle(2.5, 3.1, "red");
System.out.println("Width is: " + rect.getWidth());
System.out.println("Height is: " + rect.getHeight());
System.out.println("Color is: " + rect.getColor());
System.out.println("Area is: " + rect.getArea());

rect.setColor("blue");
System.out.println("New color is: " + rect.getColor());

rect.setWidth(4.3);
rect.setHeight(5.6);
System.out.println("New area is: " + rect.getArea());


定义Rectangle类,定义属性和计算面积的方法,代码如下:

public class Rectangle {  
    private double width;  
    private double height;  
    private String color;  
  
    public Rectangle(double width, double height, String color) {  
        this.width = width;  
        this.height = height;  
        this.color = color;  
    }  
  
    public double getWidth() {  
        return width;  
    }  
  
    public void setWidth(double width) {  
        this.width = width;  
    }  
  
    public double getHeight() {  
        return height;  
    }  
  
    public void setHeight(double height) {  
        this.height = height;  
    }  
  
    public String getColor() {  
        return color;  
    }  
  
    public void setColor(String color) {  
        this.color = color;  
    }  
  
    public double getArea() {  
        return width * height;  
    }  
}

定义主函数,调用Rectangle类,代码如下:

public class Main {  
    public static void main(String[] args) {  
        Rectangle rectangle = new Rectangle(5.0, 3.0, "red");  
        System.out.println("Width: " + rectangle.getWidth());  
        System.out.println("Height: " + rectangle.getHeight());  
        System.out.println("Color: " + rectangle.getColor());  
        System.out.println("Area: " + rectangle.getArea());  
    }  
}

运行结果:

img