Saturday, 23 April 2016

How to declare enums outside and inside the class ?


Enum outside the class
enum CoffeeSize { SMALL, MEDIUM, LARGE}

class Coffee {
     CoffeeSize size;
}
public class Test {
     public static void main(String[] args) {
         Coffee drink = new Coffee();
         drink.size = CoffeeSize.BIG; // enum outside class
     }
}



Enums inside the class
class Coffee2 {
     enum CoffeeSize {SMALL, MEDIUM, LARGE }

     CoffeeSize size;
}
public class CoffeeTest2 {
     public static void main(String[] args) {
          Coffee2 drink = new Coffee2();
          drink.size = Coffee2.CoffeeSize.BIG;
     }
}
Note:
 - Enums cannot be declared inside the methods.
 - Enums cannot be private or protected.
 - Semicolon is optional for enum, like :
  enum CoffeeSize {SMALL, MEDIUM, LARGE };

No comments:

Post a Comment

Note: only a member of this blog may post a comment.