3、抽象类: 定义表示二维形状的抽象类Shape,抽象方法有求面积和求周长。定义Shape的子类Circle表示圆,在其中实现抽象方法; 定义Shape的子类 Rectangle表示矩形,在其中实现抽象方法;创建测试类,求半径为10的圆的面积、周长;求长10宽5的矩形的面积、周长。
时间: 2023-05-27 08:07:50 浏览: 92
Java:使用抽象类定义一个“形状类”,能够计算周长和面积。
代码如下:
```
public abstract class Shape {
public abstract double getArea();
public abstract double getPerimeter();
}
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
@Override
public double getPerimeter() {
return 2 * Math.PI * radius;
}
}
public class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double getArea() {
return length * width;
}
@Override
public double getPerimeter() {
return 2 * (length + width);
}
}
public class Test {
public static void main(String[] args) {
Circle circle = new Circle(10);
System.out.println("圆的面积:" + circle.getArea());
System.out.println("圆的周长:" + circle.getPerimeter());
Rectangle rectangle = new Rectangle(10, 5);
System.out.println("矩形的面积:" + rectangle.getArea());
System.out.println("矩形的周长:" + rectangle.getPerimeter());
}
}
```
输出结果为:
```
圆的面积:314.1592653589793
圆的周长:62.83185307179586
矩形的面积:50.0
矩形的周长:30.0
```
阅读全文