抽象类(面积计算问题)
原创
©著作权归作者所有:来自51CTO博客作者B.Y的原创作品,请联系作者获取转载授权,否则将追究法律责任
package programT5_3;
/**
* 编写一个抽象类Shape,声明计算图形面积的抽象方法。
* 再分别定义Shape的子类Circle(圆)和Rectangle(矩形),
* 在两个子类中按照不同图形的面积计算公式,实现Shape类中计算面积的方法。
* @author Administrator
*
*/
public abstract class Shape {
abstract void area1();
}
package programT5_3;
public class Circle extends Shape {
private double r;
private double area;
public double getArea() {
return area;
}
public void setArea(double area) {
this.area = area;
}
public double getR() {
return r;
}
public void setR(double r) {
this.r = r;
}
@Override
public void area1() {
area=3.14*r*r;
System.out.println("半径为"+r+"的圆面积为:"+String.format("%.2f", area));
}
}
package programT5_3;
public class Rectangle extends Shape {
private double a;
private double b;
private double area;
public double getA() {
return a;
}
public void setA(double a) {
this.a = a;
}
public double getB() {
return b;
}
public void setB(double b) {
this.b = b;
}
public double getArea() {
return area;
}
public void setArea(double area) {
this.area = area;
}
@Override
public void area1() {
area=a*b;
System.out.println("边长为:"+a+"和"+b+"的矩形面积为:"+String.format("%.2f", area));
}
}
package programT5_3;
public class TestArea {
public static void main(String[] args) {
Circle c=new Circle();
Rectangle rect=new Rectangle();
c.setR(3.89);
rect.setA(3.56);
rect.setB(8.35);
c.area1();
rect.area1();
}
}