面向对象的方式计算矩形面积,Java代码
时间: 2023-03-12 08:30:31 浏览: 102
计算矩形面积的Java代码如下:
public class Rectangle {
private int length;
private int width;
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getArea() {
return length * width;
}
}
相关问题
java使用面向对象编程求矩形面积
首先,我们需要定义一个矩形类,包含矩形的长度和宽度属性,以及计算面积的方法。
代码如下:
```
public class Rectangle {
private double length; // 矩形长度
private double width; // 矩形宽度
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 static void main(String[] args) {
Rectangle rectangle = new Rectangle(10, 5); // 创建一个长为10,宽为5的矩形对象
double area = rectangle.getArea(); // 计算矩形面积
System.out.println("矩形面积为:" + area);
}
```
输出结果为:
```
矩形面积为:50.0
```
用java面向对象编程,实现计算圆形和矩形的面积和周长
好的,这是一个技术问题,我很乐意为您解答。对于计算圆形和矩形的面积和周长,您需要先定义一个圆形类和一个矩形类,并在其中分别定义计算面积和周长的方法。以下是可能的实现:
```java
// 圆形类
public class Circle {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
public double getPerimeter() {
return 2 * Math.PI * radius;
}
}
// 矩形类
public class Rectangle {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
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 double getArea() {
return width * height;
}
public double getPerimeter() {
return 2 * (width + height);
}
}
```
使用以上代码,您可以创建圆形和矩形的对象,并调用各自的方法来计算面积和周长。例如:
```java
Circle circle = new Circle(5);
System.out.println("圆形的面积为:" + circle.getArea());
System.out.println("圆形的周长为:" + circle.getPerimeter());
Rectangle rectangle = new Rectangle(3, 4);
System.out.println("矩形的面积为:" + rectangle.getArea());
System.out.println("矩形的周长为:" + rectangle.getPerimeter());
```
以上代码输出的结果应该为:
```
圆形的面积为:78.53981633974483
圆形的周长为:31.41592653589793
矩形的面积为:12.0
矩形的周长为:14.0
```