3. (15分) 编写程序,实现图形面积计算功能:
(1) 定义抽象类Shape,包含抽象方法:void printArea();
(2) 定义Shape的派生类Circle,包含一个int型radius字段,用于描述圆形的半径长度;实现printArea方法,计算并输出圆形的面积(PI=3.14);
(3) 定义Shape的派生类Square,包含一个int型sideLength字段,用于描述正方形边长;实现printArea方法,计算并输出正方形的面积;
(4) 定义ShapeTest类,在main方法中使用多态的形式测试上述printArea方法。
package project3;
public abstract class Shape {
public abstract void printArea();
}
class Circle extends Shape{
private static final float PI=(float) 3.14;
private int radius;
@Override
public void printArea() {
// TODO Auto-generated method stub
System.out.println("该圆形的面积是:"+PI*radius*radius);
}
public Circle(int radius) {
super();
this.radius = radius;
}
}
class Square extends Shape{
private int sideLength;
@Override
public void printArea() {
// TODO Auto-generated method stub
System.out.println("该正方形的面积是:"+sideLength*sideLength);
}
public Square(int sideLength) {
super();
this.sideLength = sideLength;
}
}
class ShapeText{
public static void main(String[] args) {
Shape a=new Circle(3);
Shape b=new Square(5);
a.printArea();
b.printArea();
}
}