gpt4 book ai didi

java - 根据构造函数参数构造子类?

转载 作者:行者123 更新时间:2023-12-02 02:35:00 26 4
gpt4 key购买 nike

如果我有一个抽象类及其子类:

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

有没有办法通过简单地使用构造函数重载来初始化新的 Dog 或 Fish?

类似于:

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

关于java - 根据构造函数参数构造子类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46505413/

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