Home > Java > JavaBase > body text

A brief discussion on java enumeration classes (with code)

Release: 2019-11-25 16:57:02
forward
2062 people have browsed it

A brief discussion on java enumeration classes (with code)

Introduction to java enumeration class: (java learning video recommendation: java video tutorial)

1. Under what circumstances is the enumeration class used?

Sometimes the objects of a class are limited and fixed. In this case, it is more convenient for us to use an enumeration class.

2. Why not use static constants to replace enumeration classes?

public static final int SEASON_SPRING = 1;    
public static final int SEASON_SUMMER = 2;    
public static final int SEASON_FALL = 3;    
public static final int SEASON_WINTER = 4;
Copy after login

The enumeration class is more intuitive and type safe. Using constants will have the following defects:

1. Type unsafe. If a method requires the parameter of season to be passed in, if a constant is used, the formal parameter will be of type int. The developer can pass in any type of int value, but if it is an enumeration type, it can only be passed into the enumeration class. Contained objects.

2. No namespace. Developers should start with SEASON_ when naming, so that when another developer looks at this code, they will know that these four constants represent seasons.

3. Getting started with enumeration classes

Let’s first look at a simple enumeration class.

package enumcase;public enum SeasonEnum {
    SPRING,SUMMER,FALL,WINTER;
}
Copy after login

enum has the same status as class and interface. Enumeration classes defined using enum inherit java.lang.Enum by default instead of inheriting the Object class. An enumeration class can implement one or more interfaces. All instances of the enumeration class must be displayed on the first line, without using the new keyword and without explicitly calling the constructor. Automatically add public static final modification. Non-abstract enumeration classes defined using enum are decorated with final by default and cannot be inherited. The constructor of an enumeration class can only be private.

4. Introduction to enumeration classes

Attributes and methods can also be defined in enumeration classes, but they are static and non-static.

package enumcase;public enum SeasonEnum {
    SPRING("春天"),SUMMER("夏天"),FALL("秋天"),WINTER("冬天");    
    private final String name;    
    private SeasonEnum(String name)
    {        this.name = name;
    }    public String getName() {        return name;
    }
}
Copy after login

In fact, when writing an enumeration class instance in the first line, the constructor is called by default, so parameters need to be passed in here, because the parameterless constructor is not explicitly declared and can only be called Constructor with parameters.

The constructor needs to be defined as private, so that such objects cannot be declared elsewhere. Enumeration classes should usually be designed as immutable classes, and their fields should not be changed. This will be safer and the code will be more concise. So we modify the Field with private final.

5. Enumeration class implements interface

An enumeration class can implement one or more interfaces. Like ordinary classes, when implementing an interface, you need to implement all the methods defined in the interface. If it is not fully implemented, then the enumeration class is abstract, but there is no need to explicitly add the abstract modification. Systematization will add it by default.

package enumcase;

public enum Operation {
    PLUS{

        @Override
        public double eval(double x, double y) {
            return x + y;
        }
        
    },
    MINUS{

        @Override
        public double eval(double x, double y) {
            return x - y;
        }
        
    },
    TIMES{

        @Override
        public double eval(double x, double y) {
            return x * y;
        }
        
    },
    DIVIDE{

        @Override
        public double eval(double x, double y) {
            return x / y;
        }
        
    };
    
    /**
     * 抽象方法,由不同的枚举值提供不同的实现。
     * @param x
     * @param y
     * @return
     */
    public abstract double eval(double x, double y);
    
    public static void main(String[] args) {
        System.out.println(Operation.PLUS.eval(10, 2));
        System.out.println(Operation.MINUS.eval(10, 2));
        System.out.println(Operation.TIMES.eval(10, 2));
        System.out.println(Operation.DIVIDE.eval(10, 2));
    }
}
Copy after login

The Operatio class is actually abstract and cannot create enumerated values, so when declaring enumerated values ​​here, abstract methods are implemented. This is actually the implementation of anonymous inner classes, curly braces Part is a class body. We can take a look at the compiled files.

A total of five class files were generated, which proves that PLUS, MINUS, TIMES, and DIVIDE are instances of Operation's anonymous internal classes.

A brief discussion on java enumeration classes (with code)

6. The expression in the switch statement can be an enumeration value

Java5 has added the enum keyword and expanded switch.

package enumcase;

public class SeasonTest {
    public void judge(SeasonEnum s)
    {
        switch(s)
        {
        case SPRING:
            System.out.println("春天适合踏青。");
            break;
        case SUMMER:
            System.out.println("夏天要去游泳啦。");
            break;
        case FALL:
            System.out.println("秋天一定要去旅游哦。");
            break;
        case WINTER:
            System.out.println("冬天要是下雪就好啦。");
            break;
        }
    }
    
    public static void main(String[] args) {
        SeasonEnum s = SeasonEnum.SPRING;
        SeasonTest test = new SeasonTest();
        test.judge(s);
    }
}
Copy after login

Write the enumeration value directly into the case expression without adding the enumeration class as a limitation.

Recommended: java basic tutorial

The above is the detailed content of A brief discussion on java enumeration classes (with code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template