Explain java enumeration usage and examples in detail
- 2020-06-23 00:22:32
- OfStack
1. Enumeration types as constants
package myenum;
/**
* @author zzl
* Simple enumerations act as constants
*/
public enum Color {
GREEN,RED,YELLOW;
public static void main(String[] args) {
for (Color c : values()) {
System.out.println("color:"+c);
}
}
}
// The output
/**
color:GREEN
color:RED
color:YELLOW
*/
In fact, we can print out the specific location of each enumeration instance in step 1
package myenum;
/**
* @author zzl
* Simple enumerations act as constants
*/
public enum Color {
GREEN,RED,YELLOW;
public static void main(String[] args) {
for (Color c : values()) {
System.out.println(c + " position "+c.ordinal());
}
}
}
// The output
/**
GREEN position 0
RED position 1
YELLOW position 2
*/
2. Use in combination with swith
public enum Color {
GREEN,RED,YELLOW;
public static void main(String[] args) {
Color c = RED;
switch (c) {
case RED:
System.out.println(" red ");
break;
case GREEN:
System.out.println(" green ");
break;
case YELLOW:
System.out.println(" yellow ");
break;
default:
break;
}
}
}
// The output
/**
red
*/
As you can see from the above example, the polymorphism of enumeration can actually be described as Color as the superclass of enumeration, where instances show polymorphism at runtime. (The above output is red, the following example verifies this 1 feature.)
3. Polymorphism (adding abstract methods to Color)
public enum Color {
GREEN{
void description(){
System.out.println(" Green light! ");
}
},RED{
void description(){
System.out.println(" The red light stopped! ");
}
},YELLOW{
void description(){
System.out.println(" The yellow light is on and so on 1 Etc.! ");
}
};// If there is a square rule in the enumeration after left 1 An example is ";" The end of the
abstract void description();
public static void main(String[] args) {
for (Color c : values()) {
c.description();
}
}
}
<pre name="code" class="java">// The output
/**
Green light!
The red light stopped!
The yellow light is on and so on 1 Etc.!
*/
4. Add a description for an instance using a constructor
public enum ColoStructure {
GREEN(" green "),RED(" red "),YELLOW(" yellow ");// If there is a square rule in the enumeration after left 1 An example is ";" The end of the
public String description;
private ColoStructure(String des){
this.description = des;
}
public static void main(String[] args) {
for (ColoStructure c : values()) {
System.out.println(c.description);
}
}
}
<pre name="code" class="java"><pre name="code" class="java">// The output
/**
green
red
yellow
*/
I hope this article can help friends in need