JAVA (1)设计一个形状类Shape,包含一个getArea()方法,该方法不包含实际语句
发布网友
发布时间:2022-05-20 20:19
我来回答
共1个回答
热心网友
时间:2023-11-22 13:09
abstrat class Shape{
protected abstract float getArea();
}
class Circle extends Shape{
public Circle(float radius){
this.radius=radius;
}
private float radius;
public float getArea(){
return 3.14*radius*radius;
}
}
class Rectangle extends Shape{
private float width;
private float height;
public Rectangle(float width,float height){
this.width=width;
this.height=height;
}
public float getArea(){
return width*height;
}
}
class Triangle extends Shape{
private float hemline;
private float height;
public Triangle(float hemline,float height){
this.hemline=hemline;
this.height=height;
}
public float getArea(){
return 1/2*hemline*height;
}
}
class Trapezoid extends Shape{
private float topLine;
private float bottomLine;
private float height;
public Trapezoid(float topLine,float bottomLine,float height){
this.topLine=topLine;
this.bottomLine=bottomLine;
this.height=height;
}
public float getArea(){
return 1/2*height*(topLine+bottomLine);
}
}
public class TestShape{
private float area=0.0f;
public static void countArea(Shape s){
area+=s.getArea();
}
public static void main(String[] args){
Shape s1=new Circle(1);
countArea(s1);
Shape s2=new Rectangle(1,1);
countArea(s2);
Shape s3=new Triangle(1,1);
countArea(s3);
Shape s4=new Trapezoid(1,2,1);
countArea(s4);
System.out.println("area="+area);
}
}