1、编写抽象类Shape,具有getArea()、getPerimeter()方法。
2、编写类Circle、Rectangle、Triangle,都继承Shape类,并实现2个抽象方法。
3、编写测试类TestShape,其中的main方法中完成以下功能:
分别定义三个Shape类型变量p1、p2、p3,并分别用Circle、Rectangle、Triangle创对象
分别打印出三个对象的面积和周长。
1 回答
已采纳
奔跑的虫子
TA贡献33条经验 获得超21个赞
//抽象类 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
添加回答
举报
0/150
提交
取消