Java 多态实现图形面积和周长计算
import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int code = scanner.nextInt(); Shape shape; switch (code) { case 1: double radius = scanner.nextDouble(); shape = new Circle(radius); break; case 2: double length = scanner.nextDouble(); double width = scanner.nextDouble(); shape = new Rectangle(length, width); break; case 3: double a = scanner.nextDouble(); double b = scanner.nextDouble(); double c = scanner.nextDouble(); shape = new Triangle(a, b, c); break; default: shape = null; break; } if (shape != null) { System.out.printf(".2f .2f", shape.area(), shape.circumference()); } } }
abstract class Shape { public abstract double area();
public abstract double circumference();
}
class Circle extends Shape { private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double area() {
return Math.PI * radius * radius;
}
@Override
public double circumference() {
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;
}
@Override
public double area() {
return length * width;
}
@Override
public double circumference() {
return 2 * (length + width);
}
}
class Triangle extends Shape { private double a; private double b; private double c;
public Triangle(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public double area() {
double p = (a + b + c) / 2;
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
@Override
public double circumference() {
return a + b + c;
}
}
原文地址: https://www.cveoy.top/t/topic/j9XM 著作权归作者所有。请勿转载和采集!