You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
64 lines
1.8 KiB
64 lines
1.8 KiB
public abstract class Shape {
|
|
public abstract double getArea();
|
|
public abstract void draw();
|
|
}
|
|
class Circle extends Shape {
|
|
private double radius;
|
|
public Circle(double radius) {
|
|
this.radius = radius;
|
|
}
|
|
public double getArea() {
|
|
return Math.PI * radius * radius;
|
|
}
|
|
public void draw() {
|
|
System.out.println("Drawing a circle with radius " + radius);
|
|
}
|
|
}
|
|
class Rectangle extends Shape {
|
|
private double width, height;
|
|
public Rectangle(double width, double height) {
|
|
this.width = width;
|
|
this.height = height;
|
|
}
|
|
public double getArea() {
|
|
return width * height;
|
|
}
|
|
public void draw() {
|
|
System.out.println("Drawing a rectangle with width " + width + " and height " + height);
|
|
}
|
|
}
|
|
class Triangle extends Shape {
|
|
private double base, height;
|
|
public Triangle(double base, double height) {
|
|
this.base = base;
|
|
this.height = height;
|
|
}
|
|
public double getArea() {
|
|
return 0.5 * base * height;
|
|
}
|
|
public void draw() {
|
|
System.out.println("Drawing a triangle with base " + base + " and height " + height);
|
|
}
|
|
}
|
|
class ShapeUtil {
|
|
public static void printArea(Shape shape) {
|
|
System.out.println("面积:" + shape.getArea());
|
|
}
|
|
public static void drawShape(Shape s) {
|
|
s.draw();
|
|
}
|
|
}
|
|
class Main {
|
|
public static void main(String[] args) {
|
|
Shape circle = new Circle(5);
|
|
Shape rect = new Rectangle(4, 6);
|
|
Shape tri = new Triangle(3, 4);
|
|
ShapeUtil.printArea(circle);
|
|
ShapeUtil.printArea(rect);
|
|
ShapeUtil.printArea(tri);
|
|
System.out.println("\nDrawing shapes:");
|
|
ShapeUtil.drawShape(circle);
|
|
ShapeUtil.drawShape(rect);
|
|
ShapeUtil.drawShape(tri);
|
|
}
|
|
}
|