英文:
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>
专注分享java语言的经验与见解,让所有开发者获益!
评论