设计一个形状类Shape,方法:求周长和求面积 形状类的子类:Rect(矩形),Circle(圆形) Rect类的子类:Square(正方形)

package homework;
/*1.设计一个形状类Shape,方法:求周长和求面积
形状类的子类:Rect(矩形),Circle(圆形)
Rect类的子类:Square(正方形)
不同的子类会有不同的计算周长和面积的方法
创建三个不同的形状对象,放在Shape类型的数组里,
分别打印出每个对象的周长和面积*/


public class Shape {
double sum=0;//周长
double area=1;//面积


public double getGirth() {
return 0.0;
}
public double getArea() {
return 0.0;
}

public static void main(String[] args) {
// TODO Auto-generated method stub
Rect r=new Rect(3.0,4.0);
Circle c=new Circle(3.0);
Square s=new Square(4.0);
Shape[] shapes=new Shape[3];
shapes[0]=r;
shapes[1]=c;
shapes[2]=s;
for(int i=0;i<shapes.length;i++) {
System.out.println("周长为:"+shapes[i].getGirth()+" "+"面积为:"+shapes[i].getArea());
}
}

}



package homework;


public class Circle extends Shape{
final double a=3.14159265;
double radius;

public Circle(double radius) {
this.radius=radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public double getGirth() {
sum=2*a*radius;
return sum;
}
public double getArea() {
area=a*radius*radius;
return area;
}
public static void main(String[] args) {
// TODO Auto-generated method stub


}


}


package homework;


public class Rect extends Shape{
double length;//长
double wide;//宽
public Rect(double length,double wide) {
this.length=length;
this.wide=wide;
}
public Rect() {}

public double getLength() {
return length;
}


public void setLength(double length) {
this.length = length;
}


public double getWide() {
return wide;
}


public void setWide(double wide) {
this.wide = wide;
}


public double getGirth() {
sum=2*(this.length+this.wide);
return sum;
}
public double getArea() {
area=this.length*this.wide;
return area;
}
public static void main(String[] args) {
// TODO Auto-generated method stub


}


}


package homework;


public class Square extends Rect{
public Square(double length) {
this.length=length;
}
public double getGirth() {
sum=4*length;
return sum;
}
public double getArea() {
area=length*length;
return area;
}
public static void main(String[] args) {
// TODO Auto-generated method stub


}


}

  • 24
    点赞
  • 103
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值