Based on the Java enumeration class comprehensive application

  • 2020-04-01 01:56:23
  • OfStack

Take the following code for example:


public class Test {

     public static void main(String[] args) {
         Trafficlight light = Trafficlight.RED;

         System.out.println(light.time);
         System.out.println(light.nextLigth());
         //The ordinal() method returns the order of enumeration declarations
         System.out.println(light.ordinal());
         //The values() method gets an array of all the enumerated types
         for(Trafficlight light1:light.values()){
             System.out.println(light1.name());
         }

         //The valueOf() method converts a string to the corresponding enumeration object
         System.out.println(light.RED ==light.valueOf("RED"));
     }

     public enum Trafficlight {
         GREEN(30) {

             @Override
             public Trafficlight nextLigth() {
                 return RED;
             }
         },
         RED(30) {

             @Override
             public Trafficlight nextLigth() {
                 return YELLOW;
             }
         },
         YELLOW(10) {

             @Override
             public Trafficlight nextLigth() {
                 return GREEN;
             }
         };
         public abstract Trafficlight nextLigth();

         private int time;

         //A constructor
         private Trafficlight(int time) {
             this.time = time;
         }

         public int getTime(){
             return time;
         }

     }

 }

In the code, you can see that GREEN,RED, and YELLOW are each subclasses of Trafficlight and act as its member variables. Trafficlight has an abstract method nextLight() that must be implemented in subclasses, so @override, and they also inherit from the parent class's methods, so they can call the parent class's method getTiime(). Since the parent Trafficlight class declares that a constructor with arguments overrides a constructor without arguments, subclasses must also be built with arguments.

In the code, light is just equivalent to an instance of the parent class, which can be used to obtain subclasses of various member variables and call various methods. The valueOf(String) method can convert the String into an enumeration.


Related articles: