图形(Shape)接口和它的实现类:长方形(Rectangle)、正方形(Square)和圆形(Circle)
要求:
(1)每一种图形都求它的周长double length()。
(2)在长方形类中定义长length、宽width两个属性;在正方形类中定义边长x;在圆形类中定义半属性径r。
(3)在长方形类中定义带有两个参数的构造方法用于给长和宽赋值;在正方形类中定义带有一个参数的构造方法用于给边长赋值;在圆形类中定义一个带有一个参数的构造方法用于给半径赋值。
(4)在测试类中定义一个方法shapeLength可以接收任意类型的图形对象,在方法内部调用图形周长方法。
(5)在测试类中调用shapeLength方法求长方形、正方形、圆形的周长。
(6)在主方法中定义匿名内部类作为参数传递给shapeLength方法,计算边长为5的正六边形周长。
interface Shape {
double length(); // 求周长
}
// 长方形类
class Rectangle implements Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double length() {
return 2 * (this.length + this.width);
}
}
// 正方形类
class Square implements Shape {
private double x;
public Square(double x) {
this.x = x;
}
public double length() {
return 4 * x;
}
}
// 圆形类
class Circle implements Shape {
private double r;
public Circle(double r) {
this.r = r;
}
public double length() {
return 2 * Math.PI * r;
}
}
public class ShapeTest {
// 方法接收任意类型的图形对象,并调用其周长方法
public static void shapeLength(Shape shape) {
System.out.println("周长: " + shape.length());
}
public static void main(String[] args) {
// 调用shapeLength方法求周长
Rectangle rectangle = new Rectangle(5, 3);
shapeLength(rectangle);
Square square = new Square(4);
shapeLength(square);
Circle circle = new Circle(7);
shapeLength(circle);
// 使用匿名内部类计算边长为5的正六边形周长
shapeLength(new Shape() {
public double length() {
return 6 * 5;
}
}); // 输出: 周长: 30.0
}
}