开发者

Enums in java compile error

I'm trying to learn java from bottom up, and I got this great book to read http://www.amazon.com/o/ASIN/0071591060/ca0cc-20 . Now I found example in the book about declaring Enums inside a class but outside any methods so I gave it a shot :

Enum CoffeeSize { BIG, HUGE, OVERWHELMING }; 

In the book its spelled enum and I get this compile message Syntax error, insert ";" to complete BlockStatements

Are the Enums that important at all?I mean should I skip it or its possible that I will be using those some da开发者_JAVA技巧y?


This is the correct way to declare an enum inside a class:

public class Main {
  enum Foo { One, Two, Three }

  public static void main(String args[]) {
    System.out.println(Foo.One);
  }
}

You use the enum keyword, not Enum, which is the superclass of all enum instances.


As of Java 5, enum is a keyword, so capitalization is important.

As for whether you need to know them or not, it's really up to you. They weren't even a part of the language for several versions, but they really are nice to have. Quoting from the same book:

...you can guarantee that the compiler will stop you from assigning anything to a CoffeSize except BIG, HUGE, or OVERWHELMING.

Some people don't care for this, but I personally like to let the compiler do all the work I can get out of it.

(Also, the Java Tutorials are another great source for learning the basics.)


Remove the ';'. You declare Enum like this.

enum CoffeeSize { BIG, HUGE, OVERWHELMING }

For more info please visit here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜