Java之简单图形面积计算

时间:2023-12-11 20:29:02

设计一个类层次,定义一个抽象类--形状(类名:shape)。
其中包括求形状的面积抽象方法(方法名:calArea())。
继承该抽象类定义三角形(Triangle)、矩形(Rectangle)、圆(Circle)并分别存入一个数组中。
将数组中各类图形的面积输出。

Shape:

package com.cdp.shape;

public abstract class Shape {
abstract double calArea();
}

Triangle:

package com.cdp.shape;

public class Triangle extends Shape {
// 属性
private double a, h; // 构造方法
public Triangle(double a, double h) {
this.a = a;
this.h = h;
} @Override
double calArea() {
// TODO Auto-generated method stub
return a * h / 2;
} }

Rectangle:

package com.cdp.shape;

public class Rectangle extends Shape {
private double w, h; public Rectangle(double w, double h) {
this.h = h;
this.w = w;
} @Override
double calArea() {
// TODO Auto-generated method stub
return w * h;
} }

Circle:

package com.cdp.shape;

public class Circle extends Shape {
private double r; public Circle(double r) {
this.r = r;
} @Override
double calArea() {
// TODO Auto-generated method stub
return 3.14 * r * r;
} }

Task测试类:

package com.cdp.shape;

public class Task {

	public static void main(String[] args) {
// TODO Auto-generated method stub
// 定义一个形状数组
Shape[] s = new Shape[3];
// 将三角形、矩形、圆形放入数组中
s[0] = new Triangle(3, 4);
s[1] = new Rectangle(5, 6);
s[2] = new Circle(2); // 输出面积
System.out.println("三角形的面积为" + s[0].calArea());
System.out.println("矩形的面积是:" + s[1].calArea());
System.out.println("圆形的面积是:" + s[2].calArea());
} }

运行结果:

三角形的面积为6.0
矩形的面积是:30.0
圆形的面积是:12.56