设计一个抽象基类Shape,它包含一个抽象方法area(),从Shape类扩展出矩形Rectangle类和圆类Circle,这两个
设计一个抽象基类Shape,它包含一个抽象方法area(),从Shape类扩展出矩形Rectangle类和圆类Circle,这两个
类都需要重写area()方法计算其面积,编程实现其功能.
public abstract class Shape {
public abstract double area();
}
--------------------------------------------------
public class Rectangle extends Shape {
double length;//矩形的长
double width;//矩形的宽
public Rectangle(double len,double wid) {//构造方法
this.length = len;
this.width = wid;
}
@Override
public double area() {//返回矩形的面积
double area = length * width;
return area;
}
}
--------------------------------------------------
public class Circle extends Shape {
double radius;//圆的半径
public Circle(double rad) {//构造方法
this.radius = rad;
}
@Override
public double area() {//返回园的面积
double area = 3.14 * radius * radius;
return area;
}
}
--------------------------------------------------
public class MyTest {//测试类
public static void main(String[] args) {
Rectangle rec = new Rectangle(4.7, 5.1);
double recArea = rec.area();
System.out.println("矩形的长5.1,宽4.7,面积:" + recArea);
Circle cir = new Circle(6.4);
double cirArea = cir.area();
System.out.println("园的半径6.4,面积:" + cirArea);
}
}