Monday, June 18, 2012

Talking about Enums declarations

First off all we have to get a better understanding of enums declaration, it seems to be easier however there are some tricks involved. 
Let's start from the easiest part how to declare a enum or better where enums are allowed to be declared: 

1. Enums can be declared within a class like a member: 

e.g. 


Ok, that's a easy one, but be aware that the semicolon at the end of the statement is not required when there is no more statements below the enum. 
Notice that the class name is preceding the enum, it's required to access enums that are declared within a class. 

2. Enuns can be declared outside a class 

e.g. 
    
 The most important thing here is when you declare a enum outside a class it cannot be marked as private or protected like a non-inner class 
 Different from enums declared within a class here we can access the enum by using only its name. 
  
 ! Important 
 Let's see what is allowed for enums declarations. 
  
 1. We cannot declare a enum within a method. 
 2. An enum declared outside a class cannot be marked as private or protected. 
 3. None of these modifiers are allowed for enums declared outside a class: final, static and abstract. 
 4. We can mark methods that are declared in a enum outside a class as final, static and syncronized but not abstract. 
 5. All access modifiers and static modifier are allowed for enums declared as a member(inside a class). 
  
 Declaring constructors, instance variables and methods in an enum.
  
 We can declare constructors, instance variables and methods inside an enum like you do for classes, each element of enum is a instance of enum that could contain its state and behavior. 

 e.g.  

The import things here are: 

1. We cannot invoke directly the constructor, as you can see the arguments of constructors are declared with the element, in this case MALE and FEMALE. 
2. We can declare more than one argument for the constructor as well as overload it. 

The last feature that enums provide us is: 

 e.g.  



It's like a default method for the element FEMALE, all the elements when invoke printSomething() get a message "Enum Gender", unlike when FEMALE invokes that method it will get "Enum Gender for Female". 

No comments: