Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I would say none, since in all the approaches the <code>Set&lt;Food&gt;</code> is marked as <code>static final</code> thus the same set will be shared among all the instances of <code>Dog</code> class. Also, by declaring the <code>Set</code> as <code>static final</code> doesn't mean its contents cannot be modified, so in fact any client of <code>Dog</code> class or any subclass may add new Food or even clear it and all the <code>Dog</code>s will be affected.</p> <p>This approach could do:</p> <pre><code>public abstract class Dog { //this field should be final only so the variable cannot be modified protected final Set&lt;Food&gt; favoriteFood; protected Dog(Food ... food) { //now the Set cannot be modified as well favoriteFood = Collections.unmodifiableSet(new HashSet&lt;Food&gt;(Arrays.asList(food))); } //no need to be abstract, and clients cannot modify this set public Set&lt;Food&gt; getFavoriteFoods() { //I would recommend returning a new set that return favoriteFood; } //You need to check if the dog likes the food to see if its ok public boolean isFoodOk(Food food){ //not sure if your requirement is that it always should compare with CHICKEN, really odd... return getFavoriteFoods().contains(food); //Food.CHICKEN); } //IMO this method needs a complete redesign, since I don't know the details I can't provide a solution =\ //at most it can be an abstract method and let each dog subclass implement it public abstract boolean isHappy(); //boolean isHappy(){ // return isFoodOk(); //} } public class BullDog extends Dog { public BullDog() { super(Food.CHICKEN, Food.FISH); } @Override public boolean isHappy() { //define how the bulldog is happy return ...; } } </code></pre>
 

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