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

How to specify the behavior of enumeration in java

PHPz
Release: 2023-04-19 11:43:03
forward
663 people have browsed it

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);
}
Copy after login

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!

Related labels:
source:yisu.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