单独类中的枚举
有没有办法把这个测试放在一个单独的类中?我尝试过但没有成功。
public class TrafficLightprj
{
public enum TrafficLight
{
RED(1),
GREEN(2),
YELLOW(3);
private final int duration;
TrafficLight(int duration) {
this.duration = duration;
}
public int getDuration() {
return this.duration;
}
public static void main(String[] args)
{
for(TrafficLight light: TrafficLight.values())
{
System.out.println("The traffic light value is: " +light);
System.out.println("The duration of that trafic light value is: " + light.getDuration());
}
}
}
}
Is there anyway to put this test in a separate class? I tried but was unsuccessful.
public class TrafficLightprj
{
public enum TrafficLight
{
RED(1),
GREEN(2),
YELLOW(3);
private final int duration;
TrafficLight(int duration) {
this.duration = duration;
}
public int getDuration() {
return this.duration;
}
public static void main(String[] args)
{
for(TrafficLight light: TrafficLight.values())
{
System.out.println("The traffic light value is: " +light);
System.out.println("The duration of that trafic light value is: " + light.getDuration());
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我不确定我是否理解您的问题的意思,因此我将回答我认为您所问的问题。
在 Java 中,枚举可以是它自己的文件。例如,您可以有一个名为 TrafficLight 的文件,其内部内容为:
然后您可以在测试项目 (TrafficLightPrj.java) 中使用此枚举。就像这样:
I'm not sure I understand what you mean in your question, so I'll answer to what I think you are asking.
An enum can be its own file in Java. For example, you could have a file called TrafficLight which, inside, is:
You then can use this enum from your test project (TrafficLightPrj.java). Like so:
您需要将其本身放入不同的 .java 文件中。在一个 .java 文件中不能有多个公共类/枚举。
TrafficLightprj.java
TrafficLight.java
You need to put it in a different .java file itself. You can't have more than one public class / enum in a single .java file.
TrafficLightprj.java
TrafficLight.java
当然可以,但是您需要限定枚举类名称。
TrafficLightprj.TrafficLight
而不是TrafficLight
。或者,我想,导入它。我不太喜欢非私有嵌套类,并建议将枚举设为顶级。
Sure, but you need to qualify the enum class name.
TrafficLightprj.TrafficLight
instead ofTrafficLight
. Or, I guess, import it.I am not a big fan of non-private nested classes, and suggest making the enum top-level.
假设您的问题是:“如何获取 嵌套枚举< /a> 在不同的源文件中?”
这对于部分类是可能的,但是这个 java 不支持。
Assuming your question is: "How to get a nested enum in a different source file?"
This would be possible with partial classes, but this isn't supported in java.