奔跑的虫子
//抽象类
public abstract class Shape {
protected double area;
protected double perimeter;
public abstract double getArea();
public abstract double getPerimeter();
}
//圆
public class Circle extends Shape{
private double radii;
public Circle(double radii){
this.radii=radii;
}
@Override
public double getArea() {
this.area=3.14*this.radii*this.radii;
return this.area;
}
@Override
public double getPerimeter() {
this.perimeter=2*3.14*radii;
return this.perimeter;
}
}
//矩形
public class Rectangle extends Shape{
private double width;
private double height;
public Rectangle(double width,double height){
this.width=width;
this.height=height;
}
@Override
public double getArea() {
this.area=width*height;
return this.area;
}
@Override
public double getPerimeter() {
this.perimeter=2*(width+height);
return this.perimeter;
}
}
//三角形
public class Triangle extends Shape{
private double base;
private double height;
private double side2;
private double side3;
public Triangle(double base,double height,double side2,double side3){
this.base=base;
this.height=height;
this.side2=side2;
this.side3=side3;
}
@Override
public double getArea() {
this.area=base*height;
return this.area;
}
@Override
public double getPerimeter() {
this.perimeter=base+side2+side3;
return this.perimeter;
}
}
//测试类
public class TestShape {
public static void main(String[] args) {
Shape circle=new Circle(5);
System.out.println("面积"+circle.getArea()+"周长"+circle.getPerimeter());
Shape rect=new Rectangle(3,4);
System.out.println("面积"+rect.getArea()+"周长"+rect.getPerimeter());
//参数为 底边 高 另两边边长 应该也可以用勾股定理计算高
Shape triangle=new Triangle(3,4,4,5);
System.out.println("面积"+triangle.getArea()+"周长"+triangle.getPerimeter());
}
}
结果:
面积78.5周长31.400000000000002
面积12.0周长14.0
面积12.0周长12.0