当前位置:网站首页>Use and implementation of enumeration classes
Use and implementation of enumeration classes
2022-07-23 10:20:00 【Jiuming cat Xiaoyu】
Use of enumeration class
- Class has only a limited number of objects , affirmatory .
- When you need to define a set of constants , It is highly recommended to use enumeration classes
Implementation of enumeration class
- JDK1.5 You need to customize the enumeration class before
- JDK 1.5 Newly added enum Keyword is used to define enumeration classes
- If enumeration has only one object , It can be used as a single instance mode .
Enumerate the properties of a class
- The properties of enumeration class objects should not be allowed to be changed , So you should use private final modification
- Use of enumeration class private final The decorated property should be assigned a value in the constructor
- If the enumeration class explicitly defines a constructor with parameters , When listing enumeration values, the corresponding input parameters must also be listed
Custom enumeration class
- The constructor of the privatized class , Ensure that its objects cannot be created outside of the class
- Create an instance of the enumeration class inside the class . Declare as :public static final
- Object if it has instance variables , Should be declared as private final, And initialize... In the constructor
Use enum Define an enumeration class
- Instructions :
- Use enum The enumeration class defined inherits by default java.lang.Enum class , So you can't inherit other classes
- Constructors of enumeration classes can only use private Permission modifier
- All instances of an enumeration class must be explicitly listed in the enumeration class (, Separate ; ending ). The listed instance system will automatically add public static final modification
- The enumeration class object must be declared on the first line of the enumeration class
- JDK 1.5 Can be found in switch Use in expressions Enum Defines the object of the enumeration class as an expression , case Clause can directly use the name of the enumeration value , You don't need to add an enumeration class as a qualification .
Enum Class
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-Ys8WlWpV-1657712724038)(C:\Users\asus\Desktop\image-20220713164911664.png)]](/img/07/3dfd3fe7de57188b32174b6da28809.png)
- values() Method : Returns an array of objects of type enumeration . This method can easily traverse all enumeration values .
- valueOf(String str): You can turn a string into a corresponding enumeration class object . It is required that the string must be an enumeration class object “ name ”. If not , There will be runtime exceptions :IllegalArgumentException.
- toString(): Returns the name of the current enumeration class object constant
Enumeration classes that implement interfaces
- And the general Java Similar to class , Enumeration classes can implement one or more interfaces
- If each enumeration value behaves the same way when calling the implemented interface method , Then, as long as the method is implemented uniformly .
- If you need each enumeration value to behave differently in the interface method of the call implementation , Let each enumeration value implement the method separately
package com.atguigu.java;
/** * One 、 Use of enumeration class * 1. Enumeration class understanding : Class has only a limited number of objects , affirmatory . We call this class an enumeration class * 2. When you need to define a set of constants , It is highly recommended to use enumeration classes * 3. If there is only one object in the enumeration class , Can be used as the implementation method of singleton mode * * Two 、 How to define enumeration class * Mode one :jdk5.0 Before , Custom enumeration class * Mode two :jdk5.0, have access to enum Keyword definition enumeration class * * 3、 ... and 、Enum Common methods in class : * values() Method : Returns an array of objects of type enumeration . This method can easily traverse all enumeration values . * valueOf(String str): You can turn a string into a corresponding enumeration class object . It is required that the string must be an enumeration class object “ name ”. * If not , There will be runtime exceptions :IllegalArgumentException. * toString(): Returns the name of the current enumeration class object constant * * Four 、 Use enum The enumeration class defined by the keyword implements the interface * Situation 1 : Implementation interface , stay enum Class to implement abstract methods * Situation two : Let the objects of enumeration class implement the abstract methods in the interface * * @Author damao * @Date 2022/7/13 14:51 * @Version 1.0 */
public class SeasonTest {
public static void main(String[] args) {
Season spring = Season.SPRING;
System.out.println(spring);
}
}
// Custom enumeration class
class Season{
//1. Statement Season Object properties
private final String seasonName;
private final String seasonDesc;
//2. Privatize the constructor of the class and assign values to object properties
private Season(String seasonName,String seasonDesc){
this.seasonName = seasonName;
this.seasonDesc = seasonDesc;
}
//3. Provides multiple objects of the current enumeration class :public static final Of
public static final Season SPRING = new Season(" spring "," Spring flowers ");
public static final Season SUMMER = new Season(" summer "," It's hot in summer ");
public static final Season AUTUMN = new Season(" autumn "," autumn ");
public static final Season WINTER = new Season(" winter "," a world of ice and snow ");
//4. Other demands 1: Get the properties of the enumeration class object
public String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
// Other demands 2: Provide toString()
@Override
public String toString() {
return "Season{" +
"seasonName='" + seasonName + '\'' +
", seasonDesc='" + seasonDesc + '\'' +
'}';
}
}
package com.atguigu.java;
/** * Use enum Keyword definition enumeration class * explain : The enumeration class defined is inherited from by default class java.lang.Enum class * * @Author damao * @Date 2022/7/13 15:57 * @Version 1.0 */
public class SeasonTest1 {
public static void main(String[] args) {
Season1 summer = Season1.SUMMER;
System.out.println(summer);
// System.out.println(Season1.class.getSuperclass());
System.out.println("=================");
//values():
Season1[] values = Season1.values();
for (int i = 0; i < values.length; i++) {
System.out.println(values[i]);
values[i].show();
}
System.out.println("=================");
Thread.State[] values1 = Thread.State.values();
for (int i = 0; i < values1.length; i++) {
System.out.println(values1[i]);
}
System.out.println("=================");
//valueOf(String objName): On the basis of objName, Returns the name of the object in the enumeration class objName The object of
// without objName Enumeration class objects of , Throw exception :IllegalArgumentException
Season1 winter = Season1.valueOf("WINTER");
// Season1 winter = Season1.valueOf("WINTER1");
System.out.println(winter);
winter.show();
}
}
interface Info{
void show();
}
// Use enum Keyword definition enumeration class
enum Season1 implements Info{
//1. Provides the object of the current enumeration class , Use... Between multiple objects “,” separate , The end object uses “;” end
SPRING(" spring ", " Spring flowers "){
@Override
public void show() {
System.out.println(" Where is spring ?");
}
},
SUMMER(" summer ", " It's hot in summer "){
@Override
public void show() {
System.out.println(" summer ");
}
},
AUTUMN(" autumn ", " autumn "){
@Override
public void show() {
System.out.println(" autumn ");
}
},
WINTER(" winter ", " a world of ice and snow "){
@Override
public void show() {
System.out.println(" winter ");
}
};
//2. Provides multiple objects of the current enumeration class :public static final Of
private final String seasonName;
private final String seasonDesc;
//3. Privatize the constructor of the class and assign values to object properties
private Season1(String seasonName, String seasonDesc) {
this.seasonName = seasonName;
this.seasonDesc = seasonDesc;
}
//4. Other demands 1: Get the properties of the enumeration class object
public String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
// // Other demands 2: Provide toString()
//
// @Override
// public String toString() {
// return "Season1{" +
// "seasonName='" + seasonName + '\'' +
// ", seasonDesc='" + seasonDesc + '\'' +
// '}';
// }
/*@Override public void show(){ System.out.println(" It's a season "); }*/
}
边栏推荐
- [vscode] the current working directory is not the current folder /pathlib print CWD path error
- Scala object
- 利用反射对修饰符为final的成员变量进行修改
- 软考 系统架构设计师 简明教程 | 逆向工程
- Decompile the jar package / class file / modify the jar package using the decompile plug-in of idea
- 专题训练-链表
- [basics of C language] 14 file, declaration and format input and output
- leetcode-99.恢复二叉搜索树
- RDB和AOF的优缺点
- How switch statements work
猜你喜欢

Android development learning diary - content provider (cross application database modification)
![[basics of C language] 14 file, declaration and format input and output](/img/92/e7a9ec9e39349757f78aed4f5a622a.jpg)
[basics of C language] 14 file, declaration and format input and output

2. Judgment statement

深入理解MVCC与BufferPool缓存机制
![[300 + selected interview questions from big companies continued to share] big data operation and maintenance sharp knife interview question column (VII)](/img/cf/44b3983dd5d5f7b92d90d918215908.png)
[300 + selected interview questions from big companies continued to share] big data operation and maintenance sharp knife interview question column (VII)

EasyCVR平台升级到最新版本v2.5.0,如何同步mysql数据库?

宇视NVR设备接入EasyCVR平台,离线后无法上线该如何解决?

C language flexible array
![[azure event center] try new functions of azure event hub -- geo disaster recovery](/img/7a/628152d10b61fa5447564225b6f77a.png)
[azure event center] try new functions of azure event hub -- geo disaster recovery

Error msb4181: the "qtrunwork" task returned false, but no error was recorded
随机推荐
中小企业的福音来咯!JNPF渐火,助力业务数字化升级
redis分片集群如何搭建与使用
Moment get week, month, quarter, year
网络安全之ARP欺骗防护
The world is being devoured by open source software
Self organization is the two-way rush of managers and members
Network communication principle and IP address allocation principle. The seven layers of the network are physical layer, data link layer, network layer, transmission layer, session layer, presentation
金仓数据库 KingbaseES SQL 语言参考手册 (8. 函数(一))
金仓数据库 KingbaseES SQL 语言参考手册 (8. 函数(九))
金仓数据库 KingbaseES SQL 语言参考手册 (8. 函数(七))
新的项目实现的技术点如有需要可以指导
jeecgboot 导入文档
金仓数据库 KingbaseES SQL 语言参考手册 (8. 函数(五))
软考 系统架构设计师 简明教程 | 需求工程
MySQL three table query problem
世界正在被开源软件吞食
图文并茂演示小程序movable-view的可移动范围
ArcGIS calculates the correlation between two grid layers
Redis事务-秒杀案例模拟实现详细过程
【300+精选大厂面试题持续分享】大数据运维尖刀面试题专栏(七)