java编程.类. 常见平面图形(如三角形、圆、矩形和正方形等)的面积.利用抽象类,编写程序实现该

1个回答

  • abstract class Shape{

    x09abstract double area();

    }

    class Circle extends Shape {

    x09private double r;

    x09private final double PI=3.14;

    x09public Circle(double r) {

    x09x09this.r = r;

    x09}

    x09@Override

    x09double area() {

    x09x09return PI*r*r;

    x09}

    }

    class Rectangle extends Shape {

    x09private double w;

    x09private double h;

    x09public Rectangle(double w, double h) {

    x09x09this.w = w;

    x09x09this.h = h;

    x09}

    x09@Override

    x09double area() {

    x09x09return w * h;

    x09}

    }

    class Triangle extends Shape {

    x09private double h;

    x09private double l;

    x09public Triangle(double h, double l) {

    x09x09this.h = h;

    x09x09this.l = l;

    x09}

    x09@Override

    x09double area() {

    x09x09return 0.5 * h * l;

    x09}

    }

    class Square extends Rectangle {

    x09public Square(double l) {

    x09x09super(l, l);

    x09}

    }

    public class Test {

    x09public static void main(String[] args) {

    x09x09System.out.println("圆 "+new Circle(1).area());

    x09x09System.out.println("矩形 "+new Rectangle(4,2).area());

    x09x09System.out.println("正方形 "+new Square(3).area());

    x09x09System.out.println("三角形 "+new Triangle(3,4).area());

    x09}

    }