用Java写出创建Shape(图形)抽象类,该类中有一个计算面积的抽象方法getArea()和属性name。圆形(Circle)和矩形(Rectangle)都继承自图形类。输出图形和矩形的面积,新建测试类输入数据并输出结果
时间: 2024-05-14 18:14:13 浏览: 63
采用面向对象的程序设计方法编写一个计算图形面积的类,程序应当能够计算并输出圆、矩形和三角形的面积。
5星 · 资源好评率100%
抽象类 Shape 的代码:
```java
public abstract class Shape {
protected String name;
public Shape(String name) {
this.name = name;
}
public abstract double getArea();
}
```
圆形类 Circle 的代码:
```java
public class Circle extends Shape {
private double radius;
public Circle(String name, double radius) {
super(name);
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}
```
矩形类 Rectangle 的代码:
```java
public class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(String name, double width, double height) {
super(name);
this.width = width;
this.height = height;
}
@Override
public double getArea() {
return width * height;
}
}
```
测试类的代码:
```java
public class Test {
public static void main(String[] args) {
Circle circle = new Circle("圆形", 5);
Rectangle rectangle = new Rectangle("矩形", 3, 4);
System.out.println(circle.name + "的面积是:" + circle.getArea());
System.out.println(rectangle.name + "的面积是:" + rectangle.getArea());
}
}
```
输出结果:
```
圆形的面积是:78.53981633974483
矩形的面积是:12.0
```
阅读全文