在 Java 中为枚举分配自定义值

Sheeraz Gul 2023年10月12日
在 Java 中为枚举分配自定义值

Java enum 数据类型以语言支持的方式创建和使用常量值。通过定义一组有限的值,enum 变得比 int 或 string 等常量变量更安全。

本教程演示了如何在 Java 中使用自定义变量创建 enum

在 Java 中为枚举分配自定义值

让我们将自定义值附加到枚举并尝试获取和打印它们。下面的示例创建了具有相应用法的不同编程语言的枚举

package delftstack;

enum Programming_Usage {
  // enum constructor calling with one custom string value
  PYTHON("DataScience"),
  PHP("WebDevelopment"),
  JAVA("AndroidDevelopment"),
  MATLAB("ImageProcessing");

  // declare the private string to get values later
  private String usage;

  // get usage of programming language method
  public String get_usage() {
    return this.usage;
  }

  // enum constructor
  private Programming_Usage(String usage) {
    this.usage = usage;
  }
}

public class Enum_Value {
  public static void main(String args[]) {
    // This example will print usage with corresponding programming language.
    Programming_Usage[] usages = Programming_Usage.values();

    for (Programming_Usage usage : usages) {
      // use get usage method method to get the values of usage and programming language
      System.out.println(
          "For " + usage.get_usage() + ", we mostly use " + usage.name() + " programming");
    }
  }
}

上面的代码将获取枚举的自定义值并打印具有相应用法的编程语言,其中 name() 是枚举的内置方法,get_usage() 是我们定义的方法。

输出:

For DataScience, we mostly use PYTHON programming
For WebDevelopment, we mostly use PHP programming
For AndroidDevelopment, we mostly use JAVA programming
For ImageProcessing, we mostly use MATLAB programming
作者: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

相关文章 - Java Enum