Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Tutorial 43 Enum Types: Basic and Advanced Usage
- //Enums are lists of constants. When you need a predefined list of values which do not represent some kind of numeric or textual data, you should use an enum.
- //For instance, in a chess game you could represent the different types of pieces as an enum:
- /*
- enum ChessPiece {
- PAWN,
- ROOK,
- KNIGHT,
- BISHOP,
- QUEEN,
- KING;
- }
- */
- //---------------------------------------------------------------------------------------------------------------------------------------
- //App.java
- public class App {
- public static void main(String[] args) {
- Animal animal = Animal.CAT;
- switch(animal) { //click on the warning>"add missing case statements" to add cases
- case CAT:
- System.out.println("CAT");
- break;
- case DOG:
- System.out.println("DOG");
- break;
- case MOUSE:
- break;
- }
- //Let's look at more advance uses of enums:
- System.out.println(Animal.DOG);
- System.out.println(Animal.DOG.getClass());
- System.out.println(Animal.DOG instanceof Enum); //"instanceof" operator tells us if the object is an instance of(created from a particular class) the class(true or false). in this case when you run it, it should be: true
- //3*
- System.out.println(Animal.MOUSE.getName());
- System.out.println("Enum name as a string: " + Animal.DOG.name()); //get actual name of Enum
- Animal animal2 = Animal.valueOf("CAT"); //use static method "valueOf" to get name of the Enum constants //in this instance it should say "Fergus" when you run it
- System.out.println(animal2);
- }
- }
- //---------------------------------------------------------------------------------------------------------------------------------------
- //Animal enum
- //rightclick on default package>new>Enum:
- public enum Animal {
- //CAT, DOG, MOUSE
- // 3* You can give enum types a constructor
- CAT("Fergus"), DOG("Fido"), MOUSE("Jerry");
- private String name;
- Animal(String name){
- this.name = name;
- }
- public String getName() { //source>GettersandSetters>check name field
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String toString(){
- return "This animal is called: " + name;
- }
- }
- //---------------------------------------------------------------------------------------------------------------------------------------
- /* Run results:
- CAT
- This animal is called Fido
- class Animal
- true
- Jerry
- Enum name as a string: DOG
- This animal is called Fergus
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement