一篇文章让你三分钟学会Java枚举
什么是枚举
至于枚举,我们先拿生活中的枚举来入手,然后再引申Java中的枚举,其实它们的意义很相似。
谈到生活中的枚举,假如我们在玩掷骰子的游戏,在我们手中有两个骰子,要求掷出两个骰子的点数和必须大于6的概率,那么在此情此景,我们就需要使用枚举法一一列举出骰子点数的所有可能,然后根据列举出来的可能,求出概率。
可能有的小伙伴发现,这就是数学啊?这就是数学中的概率学和统计学。对,我们的枚举法就是常用于概率统计中的。
枚举类enum是jdk1.5引入的,全称enumeration,和class、interface的地位一样,存在java.lang包中
使用步骤
我认为枚举的使用方法主要分为以下几步:
一:定义枚举类型
二:定义私有变量(私有变量的数量取决于枚举类型括号里面的参数数量)
三:重载构造方法
四:编写get/set方法
五:调用枚举类
创建枚举类
/**
*创建枚举对象
*注意事项:
*一:定义枚举类型
*二:定义私有变量(私有变量的数量取决于枚举类型括号里面的参数数量)
*三:重载构造方法
*四:编写get/set方法
*/
publicenumMyEnumDemo{
//一:定义枚举类型
HELLO("hello","1","haha1"),
WORLD("world","2","haha2"),
OTHER("other","3");
//二:定义私有变量(私有变量的数量取决于枚举类型括号里面的参数数量)
privateStringdemo1;
privateStringdemo2;
privateStringdemo3;
//三:重载构造方法
MyEnumDemo(Stringdemo1,Stringdemo2){
this.demo1=demo1;
this.demo2=demo2;
}
//三:重载构造方法
MyEnumDemo(Stringdemo1,Stringdemo2,Stringdemo3){
this.demo1=demo1;
this.demo2=demo2;
this.demo3=demo3;
}
//四:编写get/set方法
publicStringgetDemo1(){
returndemo1;
}
publicvoidsetDemo1(Stringdemo1){
this.demo1=demo1;
}
publicStringgetDemo2(){
returndemo2;
}
publicvoidsetDemo2(Stringdemo2){
this.demo2=demo2;
}
publicStringgetDemo3(){
returndemo3;
}
publicvoidsetDemo3(Stringdemo3){
this.demo3=demo3;
}
}
测试枚举类
importorg.junit.Test;
publicclassDemo{
@Test
publicvoidhah(){
System.out.println("--------------------------");
System.out.println(MyEnumDemo.HELLO);
System.out.println(MyEnumDemo.HELLO.getDemo1());
System.out.println(MyEnumDemo.HELLO.getDemo2());
System.out.println(MyEnumDemo.HELLO.getDemo3());
System.out.println("--------------------------");
System.out.println(MyEnumDemo.WORLD);
System.out.println(MyEnumDemo.WORLD.getDemo1());
System.out.println(MyEnumDemo.WORLD.getDemo2());
System.out.println(MyEnumDemo.WORLD.getDemo3());
System.out.println("--------------------------");
System.out.println(MyEnumDemo.OTHER);
System.out.println(MyEnumDemo.OTHER.getDemo1());
System.out.println(MyEnumDemo.OTHER.getDemo2());
System.out.println(MyEnumDemo.OTHER.getDemo3());
System.out.println("--------------------------");
}
}
输出结果
/**
*输出结果:
*--------------------------
*HELLO
*hello
*1
*haha1
*--------------------------
*WORLD
*world
*2
*haha2
*--------------------------
*OTHER
*other
*3
*null
*--------------------------
*/
到此这篇关于三分钟学会Java枚举的文章就介绍到这了,更多相关三分钟学Java枚举内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!