Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/397.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么java中的一切不是静态函数?以下两个例子有什么不同?_Java_Class - Fatal编程技术网

为什么java中的一切不是静态函数?以下两个例子有什么不同?

为什么java中的一切不是静态函数?以下两个例子有什么不同?,java,class,Java,Class,假设有以下两个类,第一个是长方体类,第二个是描述操作的类 public class Cuboid { private double length; private double width; private double height; public Cuboid(double length, double width, double height) { super(); this.length = length;

假设有以下两个类,第一个是长方体类,第二个是描述操作的类

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);
下面的示例如何使用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;
    }
}
VS


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


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

如果你想,你可以使用statics,这取决于设计,但是如果你想比较两个长方体呢?所以如果我想保存长方体数据,那么我肯定需要方法1;如果我不需要保存数据(比如CreateVolumeBuilder类),那么我需要静态函数?
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;
    }
}