Java 基于构造函数参数构造子类?

Java 基于构造函数参数构造子类?,java,constructor,Java,Constructor,如果我有一个抽象类及其子类: 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 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.
}

构造函数是其类的一部分,因此不能重载它来创建不同的类。但是,您可以拥有一个具有重载方法的工厂:

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);
    }
}

构造函数是其类的一部分,因此不能重载它来创建不同的类。但是,您可以拥有一个具有重载方法的工厂:

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);
    }
}

您可能正在寻找工厂方法。您想让一个方法为不同的参数创建一个新对象

public static Fish makeFish(int newLegs, int newSpeed) {
    return new Fish(newLegs, newSpeed);
}

public static Dog makeDog(int newLegs) {
    return new Dog(newLegs);
}

您可能正在寻找工厂方法。您想让一个方法为不同的参数创建一个新对象

public static Fish makeFish(int newLegs, int newSpeed) {
    return new Fish(newLegs, newSpeed);
}

public static Dog makeDog(int newLegs) {
    return new Dog(newLegs);
}

根据“抽象类”的定义,不。即使它不是抽象的,因为
newsomeclass
总是创建(准确地)SomeClass的实例,不。根据“抽象类”的定义,不。即使它不是抽象的,因为
newsomeclass
总是创建(准确地)SomeClass的实例,不。