Why should I use Enum, not just a class?

I was helping a friend with Java the other day and they were asking about Enums. I explained that the syntax is C (something like)

enumeration Difficulty{
    BEGINNER= 1;
    PRO=5;
    EXPERT = 11;
}

There was no way, Java syntax something(1);you created a constructor that took an int, and then did it, etc. etc.

But they stopped me and asked: "If we use constructors, etc., why bother with listing, why not just create a new class?"

And I could not answer. So, why would you use an enumeration in this case, not a class?

+5
source share
7 answers

. enum ( new ).

JVM, , . , , EnumSet EnumMap, , (, , ).

, switch. pre-Java1.7, switch ( -, , String - , , - , , , , ).

+9

, .

  • , .
  • switch.
  • .
  • .
  • .
+6

, Enum java .

:

public enum MyEnum {
   FOO, BAR
}

public abstract class MyEnum {
    public static final MyEnum FOO = new MyEnum(){};
    public static final MyEnum BAR = new MyEnum(){};

    private MyEnum(){}
}

, , , , :

public enum Operators {
    ADD("+"){ 
        public double apply(double lhs, double rhs){ return lhs + rhs; }
    },

    SUBTRACT("-"){ 
        public double apply(double lhs, double rhs){ return lhs - rhs; }
    },

    MULTIPLY("*"){ 
        public double apply(double lhs, double rhs){ return lhs * rhs; }
    },

    DIVIDE("/"){ 
        public double apply(double lhs, double rhs){ return lhs / rhs; }
    };

    private final String symbol;

    Operators(String symbol){
        this.symbol = symbol;
    }

    public abstract double apply(double lhs, double rhs);
}

( ):

public abstract class Operators {
    public static final Operators ADD = new Operators("+"){ 
        public double apply(double lhs, double rhs){ return lhs + rhs; }
    };

    public static final Operators SUBTRACT = new Operators("-"){ 
        public double apply(double lhs, double rhs){ return lhs - rhs; }
    };

    public static final Operators MULTIPLY = new Operators("*"){ 
        public double apply(double lhs, double rhs){ return lhs * rhs; }
    },

    public static final Operators DIVIDE = new Operators("/"){ 
        public double apply(double lhs, double rhs){ return lhs / rhs; }
    };

    private final String symbol;

    private Operators(String symbol){
        this.symbol = symbol;
    }

    public abstract double apply(double lhs, double rhs);
}

, , , C. , , , .

+6

Enums -

1) Enum , enum, enum, .

2) Enum .

3). Enum - Enum Java Switch, int char . java 7 String switch.

4) Enum Java , .

+4

, , ... ehhm... enum:)

, , .

0

Since the class can have an arbitrary number of instances, while in the "enumeration" the number of instances is limited by the elements of the enumeration itself (therefore, the constructor must be private), and these instances can be accessed statically.

0
source

All Articles