Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract Classes and Enums

Tags:

java

enums

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.

like image 892
gobernador Avatar asked Jan 31 '26 20:01

gobernador


1 Answers

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.

like image 59
andersoj Avatar answered Feb 02 '26 09:02

andersoj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!