abstract class Shape { public abstract double area(); } class Circle extends Shape { private double radius; public Circle(double radius) { this.radius = radius; } @Override public double area() { return Math.PI * radius * radius; } } 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 area() { return length * width; } } class Triangle extends Shape { private double base; private double height; public Triangle(double base, double height) { this.base = base; this.height = height; } @Override public double area() { return 0.5 * base * height; } } public class PolymorphismDemo { public static void main(String[] args) { Shape[] shapes = new Shape[3]; shapes[0] = new Circle(2.0); shapes[1] = new Rectangle(3.0, 4.0); shapes[2] = new Triangle(2.0, 3.0); double totalArea = 0.0; for (Shape shape : shapes) { totalArea += shape.area(); } System.out.println("Total area: " + totalArea); } }
时间: 2023-12-15 13:45:30 浏览: 106
shape area
这段代码展示了多态的概念。Shape是一个抽象类,定义了一个抽象方法area(),表示形状的面积。Circle、Rectangle和Triangle是Shape的子类,它们都实现了area()方法,并分别表示圆、矩形和三角形。在主方法中,创建了一个Shape类型的数组shapes,并将Circle、Rectangle和Triangle的实例存储到数组中。然后,遍历shapes数组,对每个Shape对象调用area()方法,计算总面积。由于Circle、Rectangle和Triangle都是Shape的子类,它们的area()方法的实现不同,因此实现了多态的效果。
阅读全文