5 changed files with 52 additions and 0 deletions
@ -0,0 +1,12 @@ |
|||
public class Circle extends Shape { |
|||
private double radius; |
|||
|
|||
public Circle(double radius) { |
|||
this.radius = radius; |
|||
} |
|||
|
|||
@Override |
|||
public double getArea() { |
|||
return Math.PI * radius * radius; |
|||
} |
|||
} |
|||
@ -0,0 +1,14 @@ |
|||
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() { |
|||
return width * height; |
|||
} |
|||
} |
|||
@ -0,0 +1,3 @@ |
|||
public abstract class Shape { |
|||
public abstract double getArea(); |
|||
} |
|||
@ -0,0 +1,18 @@ |
|||
public class ShapeTest { |
|||
public static void main(String[] args) { |
|||
// 创建各个图形对象
|
|||
Shape c = new Circle(5); |
|||
Shape r = new Rectangle(4,6); |
|||
Shape t = new Triangle(3,4); |
|||
|
|||
//统一调用工具打印面积
|
|||
System.out.print("圆形:"); |
|||
ShapeUtil.printArea(c); |
|||
|
|||
System.out.print("矩形:"); |
|||
ShapeUtil.printArea(r); |
|||
|
|||
System.out.print("三角形:"); |
|||
ShapeUtil.printArea(t); |
|||
} |
|||
} |
|||
@ -0,0 +1,5 @@ |
|||
public class ShapeUtil { |
|||
public static void printArea(Shape shape){ |
|||
System.out.println("图形面积:" + shape.getArea()); |
|||
} |
|||
} |
|||
Loading…
Reference in new issue