为什么不是Java中的所有函数都是静态函数?以下两个示例有何不同? [英] Why not everything is static function in java? Any differences in following two examples?

查看:69
本文介绍了为什么不是Java中的所有函数都是静态函数?以下两个示例有何不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

然后下面的示例使用AWS JAVA SDK怎么样?

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


推荐答案

您的问题简化为为什么可以编写过程式时为什么要进行面向对象的编程?

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

OOP,函数式编程与过程

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

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

这篇关于为什么不是Java中的所有函数都是静态函数?以下两个示例有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆