Advertisement
karlakmkj

Mini Project - Enum

Sep 7th, 2020
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.90 KB | None | 0 0
  1. package trafficLights;
  2.  
  3. public enum TrafficLight {
  4.    
  5.     //Enums should be in Uppercase letters
  6.     RED ("Stop"),
  7.     YELLOW ("Wait"),
  8.     GREEN ("Go");
  9.  
  10.     private String action;
  11.    
  12.     //Enum constructor can only be private or default
  13.     private TrafficLight(String action) {
  14.         this.action = action;
  15.     }
  16.    
  17.     //getter
  18.     public String getAction() {
  19.         return action;
  20.     }  
  21. }
  22. =================================================================================================================================
  23. package trafficLights;
  24.  
  25. public class TrafficLightTester {
  26.  
  27.     public static void main(String[] args) {
  28.        
  29.         TrafficLight[] lights = TrafficLight.values();
  30.        
  31.         //for-each loop access Enum elements
  32.         for (TrafficLight light : lights) {
  33.             System.out.println("Light: " +light.name() + " --- " +
  34.                     "Action: " + light.getAction());
  35.         }
  36.         //use light.toString() can also give the same output
  37.     }
  38. }
  39.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement