Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enum in separate class

Tags:

java

enums

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());
            }
        }   
    }
}
like image 488
dsjoka Avatar asked Dec 02 '22 02:12

dsjoka


2 Answers

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());
        }
    }
}
like image 85
JasCav Avatar answered Dec 23 '22 03:12

JasCav


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; 
    }
} 
like image 45
adarshr Avatar answered Dec 23 '22 03:12

adarshr