Abstract classes and enumerations

I am trying to create an abstract class. I want each subclass to list the possible actions.

For example, Foois 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 a field and have child classes filling the enumeration with the actions it is capable of. How do I approach this?

If I define enum in a class, for example, give it some general steps, will it be passed to a subclass and can the subclass extend the enumeration? This may be another option.

+3
source share
2 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 can have

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

And you can use it EnumSetfor effective storage capabilities.

, , Right Thing, (, , ), EnumSet<CanDos> - .

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);
  }
}

(, , , , ). " Java" " ".

,

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

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

, ( ), , , , implements FooThatCanDo.

+4

, - , , , . , BitSet.

class Base {
    private static EnumSet actions;

    public EnumSet getActions() { return actions; }
}

class Derived extends Base {
    private static EnumSet actions;

    @Override
    public EnumSet getActions() { 
        return new EnumSet(actions).addAll(super.getActions()); 
    }
}
0

All Articles