Java中使用枚举创建对象

创建无参对象

public enum Direction {
    
    FRONT ,BEHIND,LEFT,RIGHT;
}

创建有参对象

public enum Directions{

    FRONT("前") {

        @Override
        public void show() {
            System.out.println("前");
        }

    },

    BEHIND("后") {

        @Override
        public void show() {
            System.out.println("后");
        }

    },

    LEFT("左") {

        @Override
        public void show() {
            System.out.println("左");
        }

    },
    RIGHT("右") {

        @Override
        public void show() {
            System.out.println("右");
        }

    };

    public abstract void show();

    private String name;

    private Directions(String name) {
        this.name = name;
    }

    public String getString() {
        return name;
    }
}

运行程序

public static void main(String[] args) {
    Direction d = Direction.BEHIND ;
    System.out.println(d);//BEHIND
    System.out.println("--------------------------");
        
    Directions d3 = Directions.RIGHT ;
    System.out.println(d3);//RIGHT
    d3.show();
    String name3 = d3.getString() ;
    System.out.println(name3);
        
        
    //枚举它对象都可以去调用toString()方法,返回声明实例的常量名
    String str = d3.toString() ;
    System.out.println(str);//RIGHT
        
}

你可能感兴趣的:(Java)