定义一个抽象类 Shape,其中包含求形状的面积和周长的抽象方法。定义三角形、矩形、圆形类,继承Shape。分别创建一个三角形、矩形、圆形对象,输出各类图形的面积和周长。JAVA
时间: 2024-10-10 18:01:48 浏览: 46
Java:使用抽象类定义一个“形状类”,能够计算周长和面积。
在Java中,你可以这样定义一个抽象类`Shape`以及它的派生类:
```java
// 定义抽象类 Shape
abstract class Shape {
// 抽象方法,需要在每个子类中实现
abstract double getArea();
abstract double getPerimeter();
// 具体方法,可以共用
public void display() {
System.out.println("This is a generic shape.");
}
}
// 定义三角形类,继承自 Shape
class Triangle extends Shape {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
@Override
double getArea() {
return 0.5 * base * height;
}
@Override
double getPerimeter() {
// 假设这是一个等腰三角形,仅做示例
return base + 2 * Math.sqrt((base / 2) * (height / 2));
}
@Override
void display() {
System.out.println("Triangle with base: " + base + ", height: " + height);
}
}
// 定义矩形类,同样继承自 Shape
class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
double getArea() {
return length * width;
}
@Override
double getPerimeter() {
return 2 * (length + width);
}
@Override
void display() {
System.out.println("Rectangle with length: " + length + ", width: " + width);
}
}
// 定义圆形类,继承自 Shape
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
double getArea() {
return Math.PI * radius * radius;
}
@Override
double getPerimeter() {
return 2 * Math.PI * radius;
}
@Override
void display() {
System.out.println("Circle with radius: " + radius);
}
}
public class Main {
public static void main(String[] args) {
// 创建并实例化各个形状
Triangle triangle = new Triangle(5, 6);
Rectangle rectangle = new Rectangle(4, 8);
Circle circle = new Circle(3);
// 输出各自属性
triangle.display();
System.out.println("Triangle area: " + triangle.getArea());
System.out.println("Triangle perimeter: " + triangle.getPerimeter());
rectangle.display();
System.out.println("Rectangle area: " + rectangle.getArea());
System.out.println("Rectangle perimeter: " + rectangle.getPerimeter());
circle.display();
System.out.println("Circle area: " + circle.getArea());
System.out.println("Circle perimeter: " + circle.getPerimeter());
}
}
```
当你运行这个程序时,会分别打印出每个形状的信息以及它们各自的面积和周长。这就是如何使用Java实现抽象类和多态性的基本例子。
阅读全文