Home  >  Article  >  Java  >  How to specify the behavior of enumeration in java

How to specify the behavior of enumeration in java

PHPz
PHPzforward
2023-04-19 11:43:03600browse

Explanation

1. Enumerations can not only be used to represent constants, but sometimes some simple calculation logic can also be written in the enumeration.

2. You can use abstract methods to define the behavior required for each enumeration.

Example

package com.tea.modules.java8.enums;
 
import lombok.Getter;
 
/**
 * com.tea.modules.java8.enums <br>
 * 运算符枚举
 *
 * @author jaymin
 * @since 2021/6/10
 */
@Getter
public enum OperationEnum {
    /**
     * 加
     */
    PLUS("+") {
        @Override
        public double apply(double x, double y) {
            return x + y;
        }
    },
    /**
     * 减
     */
    MINUS("-") {
        @Override
        public double apply(double x, double y) {
            return x - y;
        }
    },
    /**
     * 乘
     */
    TIMES("*") {
        @Override
        public double apply(double x, double y) {
            return x * y;
        }
    },
    /**
     * 除
     */
    DIVIDE("/") {
        @Override
        public double apply(double x, double y) {
            return x / y;
        }
    };
 
    /**
     * 运算符
     */
    private final String symbol;
 
    OperationEnum(String symbol) {
        this.symbol = symbol;
    }
 
    public abstract double apply(double x, double y);
}

The above is the detailed content of How to specify the behavior of enumeration in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete
Previous article:How to use java SortedNext article:How to use java Sorted