gpt4 book ai didi

java - 子类中的方法参数与 getter

转载 作者:行者123 更新时间:2023-12-01 23:26:59 24 4
gpt4 key购买 nike

我们在办公室进行了讨论,但双方都没有被说服。假设我们有

enum Food {
CHICKEN, HAMBURGER, FISH;
}

我们需要 Dog 的多个实现,它们需要回答它们是否快乐,这取决于它们是否喜欢给它们的食物或者其他东西。它需要非常灵活。哪个更好:答:

abstract class Dog {
//not sure if this can be abstract in reality, but does it matter?
abstract Set<Food> getFavoriteFoods();

boolean isFoodOk(){
return getFavoriteFoods().contains(Food.CHICKEN);
}

//in reality sometimes more conditions are needed here...
boolean isHappy(){
return isFoodOk();
}
}



public class BullDog extends Dog {
static final Set<Food> FAVORITE_FOODS = new HashSet<Food>();
static {
FAVORITE_FOODS.add(Food.CHICKEN);
FAVORITE_FOODS.add(Food.FISH);
}

Set<Food> getFavoriteFoods(){
return FAVORITE_FOODS;
}
}

或B:

abstract class Dog {
abstract boolean isHappy();

boolean isFoodOk(Set<Food> f){
return f.contains(Food.CHICKEN);
}
}

public class BullDog extends Dog {
static final Set<Food> FAVORITE_FOODS = new HashSet<Food>();
static {
FAVORITE_FOODS.add(Food.CHICKEN);
FAVORITE_FOODS.add(Food.FISH);
}

@Override
boolean isHappy() {
return isFoodOk(FAVORITE_FOODS);
}
}

如果答案是 A,我会有另一个问题。

注意:我编辑了代码,因为那里有一个愚蠢的错误 - 当然 FAVORITE_FOODS 应该在 BullDog 中声明,而不是 Dog。但这并不能回答问题。

最佳答案

我会说没有,因为在所有方法中 Set<Food>标记为static final因此,同一个集合将在 Dog 的所有实例之间共享。类(class)。另外,通过声明 Setstatic final并不意味着其内容不能被修改,所以实际上 Dog 的任何客户端类或任何子类可能会添加新的食物,甚至清除它和所有 Dog s将会受到影响。

这种方法可以做到:

public abstract class Dog {
//this field should be final only so the variable cannot be modified
protected final Set<Food> favoriteFood;

protected Dog(Food ... food) {
//now the Set cannot be modified as well
favoriteFood = Collections.unmodifiableSet(new HashSet<Food>(Arrays.asList(food)));
}

//no need to be abstract, and clients cannot modify this set
public Set<Food> 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 ...;
}
}

关于java - 子类中的方法参数与 getter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19838887/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com