Abstract Classes and Enums

enums, java

Solution

I don't know that I agree with the approach but you could do

enum CanDos {
  TALK,
  WALK,
  SLEEP,
  SIT,
  STARE
}

And then the class could have

abstract class Foo {
  abstract Set<CanDos> getCanDos();
  //or
  abstract boolean can(CanDos item);
}

And you can use an `EnumSet` for efficient storage of the capabilities.

If all you are looking for is the Right Thing to provide a set of enums (like the field in the parent abstract class you mention) then I think `EnumSet<CanDos>` is your guy. In that case

abstract class Foo {

  private final Set<CanDos> candos;

  protected Foo(Set<CanDos> candos) 
  {
     this.candos = new EnumSet<CanDos>(candos);
  }

  public boolean can(CanDos item) {
    return candos.contains(item);
  }
}

Alternatively you could avoid the abstract class altogether (or at least not mandate it see e.g. this question or this one). The well-regarded book Effective Java suggests "Prefer interfaces to abstract classes".

To do this, instead

enum CanDos {
  TALK,
  WALK,
  SLEEP,
  SIT,
  STARE
}

public interface FooThatCanDo {
  boolean can(CanDos item);
}

If you really think there's value in a common inheritance root (which you should think hard about) then you could provide an abstract base implementation as shown above, and declare that it `implements FooThatCanDo`.

Problem

I am trying to establish an abstract class. I want to ensure that any subclass has an enum listing its potential actions. For instance, `Foo` is an abstract class. ``` Fee extends Foo and can... TALK WALK SLEEP Bar extends Foo and can... SIT STARE ``` I want to give the parent class the field and have the child classes fill in the enum with the actions that it is capable of. How would I approach this? If I define an enum in a class, for instance, give it some generic actions, will it be passed to a subclass and could a subclass extend the enum? That could be another option.

Original source

Related problems