定义一个与所在类名称相同的枚举。

huangapple 未分类评论45阅读模式
英文:

Define an enum with the same name as the class its on

问题

我有一个名为 "Millis" 的类,存储名为 Day、Hour、Minute、Second、Millisecond 的整数,我需要一个名为 add 的方法,可以执行以下操作:

Millis m4 = new Millis(21, 45, 52, 785, 15, 12, 2018); // [21:45:52.785] 15/12/18
m4.add(Millis.DAY, 16);// [21:45:52.785] 31/12/18
m4.add(Millis.HOUR, 2);// [23:45:52.785] 31/12/18
m4.add(Millis.MINUTE, 14);// [23:59:52.785] 31/12/18
m4.add(Millis.SECOND, 7);// [23:59:59.785] 31/12/18
m4.add(Millis.MILLISECOND, 214);// [23:59:59.999] 31/12/18

如何定义 add 方法的参数?我考虑使用枚举,但我不能将枚举命名为与类相同的名称,或者我不知道是否有解决方法。

英文:

So i have a class called "Millis" that stores ints called Day, Hour, Minute, Second, Millisecond and i need a method called add that can do the following

Millis m4 = new Millis(21, 45, 52, 785, 15, 12, 2018); // [21:45:52.785] 15/12/18
m4.add(Millis.DAY, 16);// [21:45:52.785] 31/12/18
m4.add(Millis.HOUR, 2);// [23:45:52.785] 31/12/18
m4.add(Millis.MINUTE, 14);// [23:59:52.785] 31/12/18
m4.add(Millis.SECOND, 7);// [23:59:59.785] 31/12/18
m4.add(Millis.MILLISECOND, 214);// [23:59:59.999] 31/12/18

How do i define the parameters of the method add? i thought of using an enum, but i cant name the enum with the same name as the class, or i dont know a workaround for that.

答案1

得分: 0

如果你坚持要使用相同的名称,你可以使用final变量代替。

public class Millis {
    final int second = 6;
    final int minutes = 3;
    // ...
}

请记住,在为final变量分配值之后,无法更改其值。

Millis mill = new Millis(2, 3, 4);
int myNumber = mill.second;
英文:

If you insist on same name, you can use final variables instead.

public class Millis {
final int second =6;
final int minutes =3;
...
}

remember that you can not change value of final variables after assigning values.

Millis mill = new Millis(2,3,4);
int myNumber =millis.second;

答案2

得分: 0

不确定我是否喜欢那个,但这是一个解决方案:

public class Millis {

    enum Field {
      DAY,
      // ...
    }

    public static final Field DAY = Field.DAY;
    // ...
}

这个 enum 甚至可以声明为 private

注意:这个 enum 可能在自己的文件(类)中,也就是不嵌套的

英文:

not sure if I like that, but it is a solution:

public class Millis {

    enum Field {
      DAY,
      // ...
    }

    public static final Field DAY = Field.DAY;
    // ...
}

<sub>The enum can even be declared private</sub>

<sub>Note: the enum may be in a own file (class), that is, not nested</sub>

huangapple
  • 本文由 发表于 2020年4月7日 01:35:48
  • 转载请务必保留本文链接:https://java.coder-hub.com/61065593.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定