enum enumeration type use

Enumerations are very common in daily life. For example, SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY representing the week is an enumeration

From this mapping to the Java language, an enumeration class representing the week can be defined:

public enum Week {
    
    
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

The key word to define enumeration class is enum, enumeration class object can not come out through new, inside SUNDAY, MONDAY...these are actually equivalent to the instance of enumeration class Week. These are the only ones that are fixed, and new instances cannot be created externally. Direct class when referencing. Instance name

Week w = Week.MONDAY;

The enumeration class also has a constructor, which is private by default and can only be private. Observe this code

public enum Week {
    
    
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;

    Week(){
    
    
        System.out.println("hello");
    }

}

public class Test {
    
    
    public static void main(String[] args) {
    
    
        Week w = Week.FRIDAY;
    }
}

You will find results like this

❝hello hello hello hello hello hello hello❞

The constructor is executed 7 times, exactly corresponding to the number of enumeration items in the class. In fact, the creation of this type of enumeration item is equivalent to the object that other classes call the no-argument constructor new, that is, this enumeration class creates 7 instances, so 7 hellos are output

In addition to parameterless constructors, enumeration classes also have parameterized constructors

public enum Week {
    
    
    SUNDAY(7), MONDAY(1), TUESDAY(2), WEDNESDAY(3), THURSDAY(4), FRIDAY(5), SATURDAY(6);

    Week(int weekNum){
    
    
        System.out.println(weekNum);
    }

}

This time it will output:

7 1 2 3 4 5 6

Like normal classes, enumeration classes can also have member variables, instance methods, static methods, etc.

public enum Week {
    
    
    SUNDAY(7), MONDAY(1), TUESDAY(2), WEDNESDAY(3), THURSDAY(4), FRIDAY(5), SATURDAY(6);

    private int weekNum;

    Week(int weekNum){
    
    
        this.weekNum = weekNum;
    }

    public int getWeekNum() {
    
    
        return weekNum;
    }

}

use:

public class Test {
    
    
    public static void main(String[] args) {
    
    
        Week w = Week.FRIDAY;
        System.out.println(w.getWeekNum());
    }
}

output

5

Enumeration classes can also have abstract methods

public enum Week {
    
    
    SUNDAY(){
    
    
        @Override
        public void getWeekNum() {
    
    
            System.out.println(7);
        }
    },
    MONDAY() {
    
    
        @Override
        public void getWeekNum() {
    
    
            System.out.println("星期一");
        }
    },

    TUESDAY(){
    
    
        @Override
        public void getWeekNum() {
    
    
            System.out.println("礼拜二");
        }
    },
    WEDNESDAY(){
    
    
        @Override
        public void getWeekNum() {
    
    
            System.out.println("周三");
        }
    };

    public abstract void getWeekNum();
}

public class Test {
    
    
    public static void main(String[] args) {
    
    
        Week w = Week.TUESDAY;
        w.getWeekNum();
    }
}

output:

❝礼拜二❞

values(),valueOf(String name) 方法

Each enum class has two static methods

  • static Direction[] values(): returns all enumeration constants of this class;
  • static Direction valueOf(String name): Returns the Direction constant by the name of the enumeration constant. Note that this method has a different number of parameters from the valueOf() method in the Enum class
public class Test {
    
    
    public static void main(String[] args) {
    
    
        for (Week w : Week.values()) {
    
    
            System.out.println(w);
        }
        System.out.println("星期天:" + Week.valueOf("SUNDAY"));
    }
}

The result is as follows

SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY 星期天:SUNDAY

I believe that in the usual development process, you must have defined constants in this way to use:

public class Discount {
    
    
    public static final double EIGHT_DISCOUNT = 0.8;

    public static final double SIX_DISCOUNT = 0.6;

    public static final double FIVE_DISCOUNT = 0.5;
}

There is actually no problem with this definition, but if there is a method like this:


BigDecimal calculatePrice(double discount){
    
    
    //...
}

It is necessary to pass in the product discount to calculate the price. There is no type constraint when using the above constant definition. You can pass in any value of double type, and the compiler will not issue a warning. Only if you use an enum to define this case, there will be stronger type constraints:

public enum Discount {
    
    
    EIGHT_DISCOUNT(0.8), SIX_DISCOUNT(0.6), FIVE_DISCOUNT(0.5);

    private double discountNum;

    Discount(double discountNum) {
    
    
        this.discountNum = discountNum;
    }

    double getDiscountNum(){
    
    
        return discountNum;
    }
}

use

public class Test {
    
    
    public static void main(String[] args) {
    
    
        calculatePrice(Discount.EIGHT_DISCOUNT);
    }

    static BigDecimal calculatePrice(Discount discount){
    
    
        System.out.println(discount.getDiscountNum());
        //...
        return null;
    }
}

Print

0.8

used in switch

public class Test {
    
    
    public static void main(String[] args) {
    
    
        Week w = Week.MONDAY;
        switch (w) {
    
    
            case MONDAY:
                System.out.println("周一"); break;
            case TUESDAY:
                System.out.println("周二"); break;
        }
    }
}

Print

❝周一❞

Implement interface, eliminate if/else

The enumeration class we created is final modified by default and inherits the Enum class by default. Therefore, other classes cannot be inherited. But you can implement the interface

if ("dog".equals(animalType)){
    
    
    System.out.println("吃骨头");
} else if ("cat".equals(animalType)) {
    
    
    System.out.println("吃鱼干");
} else if ("sheep") {
    
    
    System.out.println("吃草");
}

How to use enumeration to eliminate if/else, look at the following code:

First define an interface, which has a general method eat()

public interface Eat {
    
    
    //吃
    String eat();
}

Then create an enumeration class to implement this interface

public enum AnimalEnum implements Eat {
    
    
    Dog(){
    
    
        @Override
        public void eat() {
    
    
            System.out.println("吃骨头");
        }
    },

    Cat() {
    
    
        @Override
        public void eat() {
    
    
            System.out.println("吃鱼干");
        }
    },

    Sheep() {
    
    
        @Override
        public void eat() {
    
    
            System.out.println("吃草");
        }
    }
}

Only one line of code is required to call:

public class Test {
    
    
    public static void main(String[] args) {
    
    
        AnimalEnum.valueOf("Cat").eat();
    }
}
❝吃鱼干❞

And in this way, if I want to add new animals in the future, I only need to add code to the enumeration class without changing any old code, which conforms to the principle of opening and closing!

Enumerations can also be used in an implementation of the singleton pattern

public class SingletonExample {
    
    

    /**
     * 构造函数私有化,避免外部创建实例
     */
    private SingletonExample(){
    
    }

    private static SingletonExample getInstance() {
    
    
        return Singleton.INSTANCE.getInstance();
    }

    private enum Singleton {
    
    
        INSTANCE;
        private SingletonExample instance;

        // JVM 保证这个方法绝对只调用一次
        Singleton() {
    
    
            instance = new SingletonExample();
        }

        public SingletonExample getInstance() {
    
    
            return instance;
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_19891197/article/details/131651500