Sunday, November 13, 2011

Enum constructor visibility

Tip: The constructor for an enum type must be package-private or private access.

We will validate this by defining Enum with public constructor and see what happens:

enum Color {

 RED, BLUE, YELLOW;

 public Color() {

  System.out.println("Color");

 }}

As you can test, this code will fail to compile.

Now let's remove the public modifier from constructor or replace it with private modifier:

enum Color {

 RED, BLUE, YELLOW;

 Color() {

  System.out.println("Color");

 }}

This time it compiles and proves today's tip. 

Available in Android Market

No comments:

Post a Comment