【图形的面积与周长计算程序】
1、案例描述
长方形和圆形都属于几何图形,都有周长和面积,并且它们都有自己的周长和面积计算公式。使用抽象类的知识设计一个程序,可以计算不同图形的面积和周长。
2、案例目的
(1)学会分析“图形的面积与周长计算程序”案例的实现思路
(2)完成“图形的面积与周长计算程序”案例的代码编写、编译及运行
(3)理解和掌握面向对象的设计过程
(4)掌握抽象类及抽象方法的使用
3、运行结果
4、代码实
package cn.itcast.example;
abstract class Shape{
//抽象方法:获取面积
public abstract double getArea();
//抽象方法:获取周长
public abstract double getPerimeter();
}
class Circle extends Shape{
private double radius = 0;//圆的半径
private final static double PI = 3.14;//常量,圆周率
//有参构造,初始化圆半径
public Circle(double radius) {
this.radius = radius;
}
//求圆面积
public double getArea() {
return PI*radius*radius;
}
//求圆周长
public double getPerimeter() {
return 2*radius*PI;
}
}
class Rectangle extends Shape{
private double length = 0;//长方形的长
private double width = 0;//长方形的宽
//有参构造,初始化长方形的长和宽
public Rectangle(double length,double width) {
super();
this.length = length;
this.width = width;
}
public double getArea() {
return this.length*this.width;
}
public double getPerimeter() {
return 2*(this.length+this.width);
}
}
class ShapeCaculate{
//可以计算任意shape子类的面积
public void calArea (Shape shape) {
System.out.println(shape.getArea());
}
//可以计算任意shape子类的周长
public void calPerimater(Shape shape) {
System.out.println(shape.getPerimeter());
}
}
public class example {
public static void main (String[] arge) {
//创建图形计算器
ShapeCaculate sc = new ShapeCaculate();
//创建长方形和圆形对象
Shape rectangle = new Rectangle(3,4);
Circle circle = new Circle(3);
//求长方形和圆形的面积
System.out.println("长方形的面积:");
sc.calArea(rectangle);
System.out.println("圆形的面积:");
sc.calArea(circle);
//求长方形和圆形的周长
System.out.println("长方形的周长:");
sc.calPerimater(rectangle);
System.out.println("圆形的周长");
sc.calPerimater(circle);
}
}
现