写一个名为Rectangle的类表示矩形。其属性包括宽width和高height颜色color,width和height都是double型的。要求该类具有:使用getter和setter的形式完成属性的访问及修改;提供计算面积的getArea()方法 。
2条回答 默认 最新
- 个人练习生xx 2023-04-18 16:37关注
初学者呀,死去的大二知识来了
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());
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报