当前位置: 首页 > 知识库问答 >
问题:

为什么在Java中不是所有的东西都是静态函数?以下两个例子有什么不同吗?[副本]

贺善
2023-03-14
public class Cuboid {
    private double length;
    private double width;
    private double height;

    public Cuboid(double length, double width, double height) {
        super();
        this.length = length;
        this.width = width;
        this.height = height;
    }

    public double getVolume() {
        return length * width * height;
    }

    public double getSurfaceArea() {
        return 2 * (length * width + length * height + width * height);
    }
}
public class Cuboid {
    public static double getVolume(double length, double width, double height) {
        return length * width * height;
    }

    public static double getSurfaceArea(double length, double width, double height) {
        return 2 * (length * width + length * height + width * height);
    }
}
double boxVolume = Cuboid.getVolume(2.0, 1.0,3.0);
public class CreateVolumeBuilder {
    private AmazonEC2 ec2;
    private int size;
    private String availabilityZone;

    public CreateVolumeBuilder(AmazonEC2 ec2, int size, String availabilityZone) {
        super();
        this.ec2 = ec2;
        this.size = size;
        this.availabilityZone = availabilityZone;
    }

    public static CreateVolumeResult getVolume() {
        CreateVolumeResult createVolumeResult = ec2
                .createVolume(new CreateVolumeRequest().withAvailabilityZone(availabilityZone).withSize(size));
        return createVolumeResult;
    }
}
public class CreateVolumeBuilder {
    public static CreateVolumeResult getVolume(AmazonEC2 ec2, int size, String availabilityZone) {
        CreateVolumeResult createVolumeResult= ec2.createVolume(new CreateVolumeRequest().withAvailabilityZone(availabilityZone).withSize(size));
        return createVolumeResult;
    }
}

共有1个答案

公西翼
2023-03-14

您的问题简化为“当您可以编写过程化的程序时,为什么还要进行面向对象的编程?”

OOP vs函数式编程vs过程式编程

除此之外,您现在还需要存储cuboid数据的地方。还是创建一个长方体对象吧?

 类似资料: