Circle类和Square类继承Shape类实现Area接口,这里看到预设代码中Circle类和Square类是由以周长为参数的构造方法实例化的,那么Circle类和Square类继承了Shape类,Shape类中有以周长为参数的构造方法,所以我们可以使用通过super关键字来调用父类的构造方法。这部分代码参考写法为:

public Circle(double s) {
    super(s);
}
public Square(double s) {
    super(s);
}

计算面积的方法getArea()可以通过重写Area接口中的getArea()实现,在Circle类和Square类中补充计算面积的逻辑。具体的计算思路这里就不赘述了,重写getArea()方法的代码参考写法为:


@Override
public double getArea() {
    return Math.PI * Math.pow((getS() / (2 * Math.PI)), 2);
}
@Override
public double getArea() {
    return Math.pow((getS() / 4), 2);
}

附上完整代码:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextDouble()) {
            double s = scanner.nextDouble();
            // Circle和Square是需要你定义的类
            System.out.println(String.format("%.3f",new Circle(s).getArea()));
            System.out.println(String.format("%.3f", new Square(s).getArea()));
        }
    }

}

class Shape {

    private double s; // 周长

    public Shape(double s) {
        this.s = s;
    }

    public double getS() {
        return s;
    }

}

interface Area {
    double getArea(); // 面积
}

// 圆形
class Circle extends Shape implements Area {

    //write your code here......

 public Circle(double s) {
        super(s);
    }

    @Override
    public double getArea() {
        return Math.PI * Math.pow((getS() / (2 * Math.PI)), 2);
    }
}

// 方形
class Square extends Shape implements Area {

    //write your code here......
  public Square(double s) {
        super(s);
    }

    @Override
    public double getArea() {
        return Math.pow((getS() / 4), 2);
    }

}