Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I don't know that I agree with the approach but you could do</p> <pre><code>enum CanDos { TALK, WALK, SLEEP, SIT, STARE } </code></pre> <p>And then the class could have</p> <pre><code>abstract class Foo { abstract Set&lt;CanDos&gt; getCanDos(); //or abstract boolean can(CanDos item); } </code></pre> <p>And you can use an <code>EnumSet</code> for efficient storage of the capabilities.</p> <p>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 <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/util/EnumSet.html" rel="nofollow noreferrer"><code>EnumSet&lt;CanDos&gt;</code></a> is your guy. In that case</p> <pre><code>abstract class Foo { private final Set&lt;CanDos&gt; candos; protected Foo(Set&lt;CanDos&gt; candos) { this.candos = new EnumSet&lt;CanDos&gt;(candos); } public boolean can(CanDos item) { return candos.contains(item); } } </code></pre> <p>Alternatively you could avoid the abstract class altogether (or at least not mandate it see e.g. <a href="https://stackoverflow.com/questions/1474249/abstract-classes-vs-interfaces">this question</a> or <a href="https://stackoverflow.com/questions/462198/java-interface-vs-abstract-class-regarding-fields">this one</a>). The well-regarded book <em>Effective Java</em> suggests "<a href="https://stackoverflow.com/questions/56867/interface-vs-base-class">Prefer interfaces to abstract classes</a>". </p> <p>To do this, instead </p> <pre><code>enum CanDos { TALK, WALK, SLEEP, SIT, STARE } public interface FooThatCanDo { boolean can(CanDos item); } </code></pre> <p>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 <code>implements FooThatCanDo</code>. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload