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开发者_StackOverflow中文版.println("The traffic light value is: " +light);
System.out.println("The duration of that trafic light value is: " + light.getDuration());
}
}
}
}
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:
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;
}
}
You then can use this enum from your test project (TrafficLightPrj.java). Like so:
public class TrafficLightprj {
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());
}
}
}
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
public class TrafficLightprj {
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());
}
}
}
TrafficLight.java
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;
}
}
Sure, but you need to qualify the enum class name. TrafficLightprj.TrafficLight
instead of TrafficLight
. Or, I guess, import it.
I am not a big fan of non-private nested classes, and suggest making the enum top-level.
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.
精彩评论