Are Java enum values instances or classes?

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).

P.S. I recently created a nerdy privacy-respecting tool called When Will I Run Out Of Money? It's available for free if you want to check it out.

This article is © Adrian Smith.
It was originally published on 13 Apr 2013
More on: Java