Why not everything is static function in java? Any differences in following two examples?
本问题已经有最佳答案,请猛点这里访问。
假设您有以下两个类,第一个是长方体类,第二个是描述操作的类。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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); } } |
为什么不使用抽象类:
1 2 3 4 5 6 7 8 9 | 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); } } |
因此,如果您想获得一个盒子的体积,只需使用以下代码:
1 | double boxVolume = Cuboid.getVolume(2.0, 1.0,3.0); |
下面的例子如何使用AWS Java SDK呢?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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
1 2 3 4 5 6 | 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; } } |
您的问题简化为"当您可以编写过程性程序时,为什么要进行面向对象的编程?"
面向对象编程vs函数式编程vs过程式编程
除此之外,您现在需要在某个地方存储您的