Why not everything is static function in java? Any

2019-09-21 22:45发布

问题:

This question already has an answer here:

  • Java: when to use static methods 21 answers

Suppose you has following two classes, first is a Cuboid class, the second one is a class to describe operations.

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);
    }
}

Why not just using abstract class:

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);
    }
}

So If you want to get volume of a box, just use the following code:

double boxVolume = Cuboid.getVolume(2.0, 1.0,3.0);

And How about the following example to use 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

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:

Your question simplifies to "Why do Object Oriented Programming when you can write Procedural?"

OOP vs Functional Programming vs Procedural

Besides that, you now need somewhere to store your Cuboid data. Might as well create a Cuboid object anyway, right?



标签: java class