-1

我正在进行一项研究,其中我不想将常量存储在接口本身中,所以我一直在寻找像枚举这样的替代方法,但我发现的另一种方法是 ....t 而不是使用接口,而是使用 final具有私有构造函数的类。(使得无法实例化或子类化该类,发送一个强烈的信息,表明它不包含非静态功能/数据。在这种情况下,我们也可以利用静态导入

Public final class KittenConstants
{
    private KittenConstants() {}

    public static final String KITTEN_SOUND = "meow";
    public static final double KITTEN_CUTENESS_FACTOR = 1;
}

两个独立的东西。1:使用静态导入而不是滥用继承。2:如果您必须有一个常量存储库,请将其设为最终类而不是接口。请告知这种方法是否正确..!!

为了避免常量接口的一些陷阱(因为你不能阻止人们实现它),应该首选具有私有构造函数的适当类(从 Wikipedia 借来的示例):

public final class Constants {

private Constants() {
    // restrict instantiation
}

public static final double PI = 3.14159;
public static final double PLANCK_CONSTANT = 6.62606896e-34;
}

并且要访问常量而不必完全限定它们(即不必在它们前面加上类名),请使用静态导入(从 Java 5 开始):

import static Constants.PLANCK_CONSTANT;
import static Constants.PI;

public class Calculations {

    public double getReducedPlanckConstant() {
        return PLANCK_CONSTANT / (2 * PI);
    }
}

请展示我们如何用枚举做同样的事情......!

4

2 回答 2

2

您可以通过枚举实现“常量”:

public enum Animal {
    Kitten("meow", 1),
    Puppy("woof", 2);

    private final String sound;
    private final double cuteness;

    Animal (String sound, double cuteness) {
        this.sound = sound;
        this.cuteness = cuteness;
    }

    public String getSound() {
        return sound;
    }

    public double getCuteness() {
        return cuteness;
    }
}

要使用:

String sound = Animal.Kitten.getSound();
double cuteness = Animal.Kitten.getCuteness();
于 2012-08-21T04:09:45.443 回答
1

The simple answer is that you can't do that with an enum. An enum defines a set of related constants with the same type.

What you have in the KittenConstants case is a set of constants with fundamentally different types. This doesn't fit the enum model. (If you change the problem a bit; e.g. by generalizing over different kinds of SFA, you can make it fit ... as @Bohemian does ... but if that's not what you are trying to achieve, enum is not the right solution.)

What you have in the Constants case is a bunch of named floating point constants that you want to use as values. (All the same type ... which helps!) Now you could declare them as an enum as follows:

    public enum Constants {
        PLANCK_CONSTANT(6.62606896e-34),
        PI(3.14.59);

        public final double value;

        Constants(double value) {this.value = value);
    }

The snag is that you need to use ".value" to access each named constant's numeric value; e.g.

    import static Constants.*;
    ....
    public double getReducedPlanckConstant() {
        return PLANCK_CONSTANT.value / (2 * PI.value);
    }

.... which is kind of ugly, and I don't think there is any way around the ugliness.

Bottom line - enums are not an ideal replacement for all kinds of constant.

于 2012-08-21T04:35:47.767 回答