我有一个包含2个构造函数的类,一个构造函数接受一个对象(鱼),另一个构造函数接受一个称为鱼的对象数组(鱼)。有一个向篮子里添加鱼的功能:
public Basket(int weight, Fish fishes) {
singleFish = true;
}
public Basket(int weight, Fish[] fishes) {
singleFish = false;
}
public boolean addFishes(Fish fish) {
//here I want to make it so that when I add a fish to a basket,
//it no longer uses the top constructor.
}
假设一个篮子以1条鱼开头,我如何才能使它取一条鱼并在取一条鱼后使用第二个构造函数?
非常感谢你。
最佳答案
public Basket(int weight, Fish fish) {
this(weight, new Fish[] {fish};
singleFish = true;
}
public Basket(int weight, Fish[] fishes) {
singleFish = fishes.length == 1;
}
或者在这里,您只需要一个带有可变参数的构造函数(
Fish...
实际上是Fish[]
类型):private final Fish[] fishes;
private final boolean singleFish;
public Basket(int weight, Fish... fishes) {
this.fishes = fishes;
singleFish = fishes.length == 1;
}
new Basket(45, hering, sardine, riba);
new Basket(75, shark);