知识库 知识库
首页
  • Hyperskill - Java

    • Java basic
    • Java OOP
    • 应知
    • 扩展
    • IO & Stream
    • Error & Exception
    • Algorithm & Data structure
    • Design pattern
    • Web
    • Spring boot
  • 练习题

    • 选择题 & 填空题
    • 代码题
  • Frank - Java与生活 (OOP)

    • 参考资料
    • Java基础
    • OOP上半部分
    • OOP下半部分
  • Frank - Java API进阶

    • Base API
    • Unit Test and main function
  • 学习笔记
  • 学习笔记

    • 数据库
  • Frank - MySQL删库跑路

    • 安装、连接、配置
    • 基本操作——数据库
    • 基本操作——表
    • 基本操作——数据
    • 数据类型
    • 列属性完整性
    • 数据库设计思维
    • 单表查询
    • 多表查询
  • 学习笔记

    • 其它
  • Frank - Linux现代方法

    • 必知
    • 命令
    • 技巧
  • 技术文档
  • Git
  • GitHub技巧
  • 前端
  • Khan Academy - 语法
  • Monthly
  • 阅读
  • Others
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 标签
  • 归档
GitHub (opens new window)

Jim FuckPPT

Java小学生
首页
  • Hyperskill - Java

    • Java basic
    • Java OOP
    • 应知
    • 扩展
    • IO & Stream
    • Error & Exception
    • Algorithm & Data structure
    • Design pattern
    • Web
    • Spring boot
  • 练习题

    • 选择题 & 填空题
    • 代码题
  • Frank - Java与生活 (OOP)

    • 参考资料
    • Java基础
    • OOP上半部分
    • OOP下半部分
  • Frank - Java API进阶

    • Base API
    • Unit Test and main function
  • 学习笔记
  • 学习笔记

    • 数据库
  • Frank - MySQL删库跑路

    • 安装、连接、配置
    • 基本操作——数据库
    • 基本操作——表
    • 基本操作——数据
    • 数据类型
    • 列属性完整性
    • 数据库设计思维
    • 单表查询
    • 多表查询
  • 学习笔记

    • 其它
  • Frank - Linux现代方法

    • 必知
    • 命令
    • 技巧
  • 技术文档
  • Git
  • GitHub技巧
  • 前端
  • Khan Academy - 语法
  • Monthly
  • 阅读
  • Others
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 标签
  • 归档
GitHub (opens new window)
  • Hyperskill - Java

    • Java basic

    • Java OOP

    • 应知

      • Theory:Functional decomposition
      • Theory:Paradigms
      • Theory:Overloading
      • Theory:Write, compile, and run
      • Theory:Annotations basics
      • Theory:JVM, JRE, and JDK
      • Theory:Jave Archive
      • Theory:Running programs on your computer
      • Theory:Enums in Java
      • Theory:Fields and methods in enum
        • Sample enum
        • Conclusion
      • Theory:StringBuilder
      • Theory:Immutability
      • Theory:Boxing and unboxing
      • Theory:Introduction to generic programming
      • Theory:Generics and Object
      • Theory:What are collections
      • Theory:The collections Framework overview
      • Theory:ArrayList
      • Theory:The List interface
      • Theory:Comparable
      • Theory:Processing strings
      • Theory:Initialization blocks
      • Theory:Introduction to API
      • Theory:Generic methods
    • 扩展

    • IO & Stream

    • Error & Exception

    • Algorithm & Data structure

    • Design pattern

    • Web

    • Spring boot

  • 练习题

  • Frank - Java与生活

  • Frank - Java API进阶

  • 学习笔记

  • Java
  • Hyperskill - Java
  • 应知
Jim
2022-09-03
目录

Theory:Fields and methods in enum

We use enums to define sets of unchangeable variables. After we defined them, we may need to extend the functionality of the enum and add values to the constants. Just like a class, an enum can have fields, constructors and methods. That's why an enum comes in handy when working with values you're not going to change.

To prove that, let's consider the following example.

# Sample enum

Suppose we have to write a program that displays the battery level of a smartphone, power bank, or any device with a discrete scale.

First of all, let's create an enum with several threshold levels that represent the battery's level of charge:

public enum ChargeLevel {
    FULL, HIGH, MEDIUM, LOW
}
1
2
3

Suppose that we need to display the level of battery charge visually. We want it to be divided into several segments and have a color indication as well, in this way:

img

To do this, we will add corresponding fields and values to our enum. When we define them, we must supply values to the constructor of the enum. Here, we created a constructor in the ChargeLevel enum and added two fields sections and color. Also, there are two methods getSections() and getColor() that return the values of fields respectively.

public enum ChargeLevel {

    FULL(4, "green"),
    HIGH(3, "green"),
    MEDIUM(2, "yellow"),
    LOW(1, "red");

    int sections;
    String color;

    ChargeLevel(int sections, String color) {
        this.sections = sections;
        this.color = color;
    }

    public int getSections() {
        return sections;
    }

    public String getColor() {
        return color;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

Note that all enum instances are created by the JVM in the same way as a static field of a class. This is the reason why an enum cannot contain a public constructor. This means we cannot create enum objects by invoking an enum constructor with the new keyword but have to choose one of the predefined instances instead. Keep in mind that if your enum contains fields and methods, you should always define them after the list of constants in the enum.

Now we have a class with additional info gathered in one place: the number of sections to highlight and the color.

System.out.println(ChargeLevel.LOW.sections); // 1
System.out.println(ChargeLevel.LOW.color); // red
1
2

It is possible to extend an enum by adding custom static methods. For example, let's add a method that finds a ChargeLevel instance by the given number of sections:

public enum ChargeLevel {

    FULL(4, "green"),
    HIGH(3, "green"),
    MEDIUM(2, "yellow"),
    LOW(1, "red");

    int sections;
    String color;

    ChargeLevel(int sections, String color) {
        this.sections = sections;
        this.color = color;
    }

    public int getSections() {
        return sections;
    }

    public String getColor() {
        return color;
    }

    public static ChargeLevel findByNumberOfSections(int sections) {
        for (ChargeLevel value: values()) {
            if (value.sections == sections) {
                return value;
            }
        }
        return null;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

Inside the findByNumberOfSections() method, we iterated over the possible values using a for-each loop. Here's an example of our method's output:

System.out.println(ChargeLevel.findByNumberOfSections(2)); // MEDIUM
1

# Conclusion

Since an enum is a special class type in Java, we can add constructors, fields, and methods to it. Thus, it is possible to enhance our enum to include the values we need. The values of the constants are defined when we declare the enum. If you want to add enum fields, methods and constructors, you should do it after the enum constants' declaration.

编辑 (opens new window)
#Java#Enum
上次更新: 2022/09/26, 16:55:15
Theory:Enums in Java
Theory:StringBuilder

← Theory:Enums in Java Theory:StringBuilder→

最近更新
01
《挪威的森林》
04-14
02
青钢影
04-14
03
Processing strings
02-18
更多文章>
Theme by Vdoing | Copyright © 2022-2023 Jim Frank | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式