-3

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;
    }
}
Study Hard
  • 195
  • 1
  • 11

1 Answers1

7

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?

Community
  • 1
  • 1
Ben M.
  • 2,370
  • 1
  • 15
  • 23
  • So if I want to save cuboid data, then I definitely needs the method 1; If I don't need to save data (Like CreateVolumeBuilder class), then I need the static function? – Study Hard Nov 24 '15 at 19:58