如果我有一个抽象类及其子类:
public abstract class Animal{
//other methods..
}
public class Dog extends Animal{
private int legs;
public Dog(int legs){
this.legs = legs;
}
}
public class Fish extends Animal{
private int legs;
private int speed;
public Fish(int legs, int speed){
this.legs = legs;
this.speed = speed;
}
}
有没有办法通过简单地使用构造函数重载来初始化新的狗或鱼?
类似的东西:
public void createNewAnimal(int new_legs, int new_speed){
new Animal(new_legs, new_speed) //Makes fish.
new Animal(new_legs) //Makes dog.
}
答案 0 :(得分:1)
构造函数是其类的一部分,因此您不能重载它以创建不同的类。但是,您可以使用重载方法的工厂:
public class AnimalFactory {
public static Animal create(int legs, int speed) {
return new Fish(legs, speed);
}
public static Animal create(int speed) {
return new Dog(speed);
}
}
答案 1 :(得分:1)
您可能正在寻找工厂方法。您希望有一个方法为不同的参数创建一个新对象。
public static Fish makeFish(int newLegs, int newSpeed) {
return new Fish(newLegs, newSpeed);
}
public static Dog makeDog(int newLegs) {
return new Dog(newLegs);
}