设计一个抽象类shape,在此基础上派生出类Rectangle和类circle,二者都具有计算对象面积的函数getArea()以及计算对象周长的函数getPerim()。 运行结果: 输入圆的半径:5圆的面积: 78.5 圆的周长:31.4 输入矩形的边长:46矩形面积: 24 矩形边长:20
时间: 2024-02-24 12:00:10 浏览: 87
c++ 形状类Shape(派生出圆类Circle和矩形类Rectangle)
好的,以下是基于你提供的要求所设计的Java代码:
```java
abstract class Shape {
public abstract double getArea(); // 抽象方法求面积
public abstract double getPerim(); // 抽象方法求周长
}
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
public double getPerim() {
return 2 * Math.PI * radius;
}
}
class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double getArea() {
return length * width;
}
public double getPerim() {
return 2 * (length + width);
}
}
public class Main {
public static void main(String[] args) {
Circle c = new Circle(5);
System.out.println("输入圆的半径:5");
System.out.println("圆的面积:" + c.getArea());
System.out.println("圆的周长:" + c.getPerim());
Rectangle r = new Rectangle(4, 6);
System.out.println("输入矩形的边长:4, 6");
System.out.println("矩形面积:" + r.getArea());
System.out.println("矩形边长:" + r.getPerim());
}
}
```
运行结果为:
```
输入圆的半径:5
圆的面积:78.53981633974483
圆的周长:31.41592653589793
输入矩形的边长:4, 6
矩形面积:24.0
矩形边长:20.0
```
阅读全文