2.定义图形类Shape,该类中有获得面积的方法getArea();定义长方形类Rect,该类是Shape的子类,类中有矩形长和宽的变量double a,double b,设置长和宽的方法setWidth()、setHeight(),使用getArea()求矩形面积;利用getArea方法实现题1中圆面积的求解。

时间:2023-03-08 17:16:03

// 图形类Shape

package d922B;

public class Shape {

double getArea(ShapePara x){

return x.getArea();

}

double getArea(Rect y)

{

return y.getA()*y.getB();

}

}

//矩形类

package d922B;

public class Rect extends Shape {

private double a, b;

public Rect(double a, double b) {

super();

this.a = a;

this.b = b;

}

public double getA() {
return a;
} public double getB() {
return b;
} public void setA(double a) {
this.a = a;
} public void setB(double b) {
this.b = b;
}

}

//主类

package d922B;

public class Test {

public static void main(String[] args) {
Shape a=new Shape();
System.out.println(a.getArea(new Circle(1)));
System.out.println(a.getArea(new Rect(15,20))); }

}

//运行结果

3.0

300.0