为什么Java中的所有功能都不是静态函数?以下两个示例有何不同?

Stu*_*ard -3 java class

假设您有以下两个类,第一个是Cuboid类,第二个是描述操作的类。

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么不只使用抽象类:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,如果要获取包装盒的体积,只需使用以下代码:

double boxVolume = Cuboid.getVolume(2.0, 1.0,3.0);
Run Code Online (Sandbox Code Playgroud)

以下示例如何使用AWS JAVA SDK?

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

VS

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Ben*_* M. 5

您的问题简化为“为什么在编写过程式程序时为什么要进行面向对象的编程?”

OOP,函数式编程,过程

除此之外,您现在需要在某个地方存储Cuboid数据。还是可以创建一个Cuboid对象,对吗?