按照要求编写Java程序

2.按如下要求编写Java程序:
(1)定义接口A,里面包含值为3.14的常量PI和抽象方法double area()。
(2)定义接口B,里面包含抽象方法void setColor(String c)。
(3)定义接口C,该接口继承了接口A和B,里面包含抽象方法void volume()。
(4)定义圆柱体类Cylinder实现接口C,该类中包含三个成员变量:底圆半径radius、
圆柱体的高height、颜色color。
(5)创建主类来测试类Cylinder

该回答引用chatgpt:有问题可以@我


// 定义接口A
interface A {
    double PI = 3.14;
    double area();
}

// 定义接口B
interface B {
    void setColor(String c);
}

// 定义接口C,继承接口A和B
interface C extends A, B {
    void volume();
}

// 圆柱体类Cylinder实现接口C
class Cylinder implements C {
    private double radius;
    private double height;
    private String color;

    // 实现接口A中的抽象方法
    @Override
    public double area() {
        return PI * radius * radius;
    }

    // 实现接口B中的抽象方法
    @Override
    public void setColor(String c) {
        color = c;
    }

    // 实现接口C中的抽象方法
    @Override
    public void volume() {
        double volume = area() * height;
        System.out.println("Volume of cylinder: " + volume);
    }
}

// 主类测试Cylinder类
public class Main {
    public static void main(String[] args) {
        Cylinder cylinder = new Cylinder();
        cylinder.radius = 5.0;
        cylinder.height = 10.0;
        cylinder.setColor("Red");
        cylinder.volume();
    }
}

我们定义了接口A、B和C,以及实现类Cylinder。接口A包含常量PI和抽象方法area(),接口B包含抽象方法setColor(),接口C继承了接口A和B,并添加了抽象方法volume()。类Cylinder实现了接口C,并实现了接口中的所有抽象方法。在主类Main中,我们创建了一个Cylinder对象,并设置了半径、高度和颜色,然后调用volume()方法计算圆柱体的体积并输出结果。

interface A {
    public static final double PI = 3.14;
    public abstract double area();
}

interface B {
    public abstract void setColor(String c);
}

interface C extends A, B {
    public abstract void volume();
}

class Cylinder implements C {
    private double radius;
    private double height;
    private String color;

    public Cylinder(double radius, double height, String color) {
        this.radius = radius;
        this.height = height;
        this.color = color;
    }

    @Override
    public double area() {
        return 2 * A.PI * radius * radius + 2 * A.PI * radius * height;
    }

    @Override
    public void setColor(String c) {
        this.color = c;
    }

    @Override
    public void volume() {
        System.out.println("The volume of the cylinder is " + A.PI * radius * radius * height);
    }

    public static void main(String[] args) {
        Cylinder cylinder = new Cylinder(10, 20, "red");
        System.out.println("The area of the cylinder is " + cylinder.area());
        System.out.println("The color of the cylinder is " + cylinder.color);
        cylinder.setColor("blue");
        System.out.println("The color of the cylinder is " + cylinder.color);
        cylinder.volume();
    }
}