Are Java enum values instances or classes?

By Adrian Smith13 Apr 2013200 words1 mins to read

That depends on if the enum values provide methods which differ from one another.

The following code produces just one class file, "Network.class". "facebook" and "linkedIn" are just instances of the Network Java class.

public enum Network {
  facebook, 
  linkedIn;

  public void printName() { System.out.println(getName()); }
}

But the following code produces one class file for each value, named "Network$1.class" etc., as well as one class file for the abstract superclass, "Network.class".

public enum Network {
  facebook {
    public Client newClient() { return new FacebookClient(); }
  },
  linkedIn {
    public Client newClient() { return new LinkedInClient(); }
  };

  public abstract Client newClient();
}

"facebook" and "linkedIn" are in fact different Java classes now.

Having a constructor taking parameters, and initializing each value of the enum by calling this constructor with values, is not sufficient to force the generation of individual classes per value.

Just because they are different classes in this situation doesn't automatically mean you can do everything you'd expect to be able to do with a class. You can't test for class membership using "instanceof" for example (not that this would be very useful for an enum, as there is only one instance of every value).

This article was written by Adrian Smith on 13 Apr 2013

Follow me: Facebook | Twitter | LinkedIn | Email

More on: Java