0

假设我有一只动物,现在我想把它变成一只狗。我该如何在java中做到这一点?

现在我有一个看起来像的构造函数

public Dog(Animal animal) {
  this.setProperty(animal.getProperty);
  ...
}

虽然这有效,但它很脆弱。还有其他建议吗?

4

4 回答 4

5

如果您的 Dog 扩展了 Animal,您可以创建一个构造函数,该构造函数接受 Animal 并初始化 super(parent) 构造函数:

public class Dog extends Animal {
    public Dog(Animal animal) {
        super(animal);
    }
}

假设您有一个 Animal 类,该类具有这种形式的复制构造函数:

public class Animal {
    public Animal(Animal animal) {
        // copies all properties from animal to this
    }
}

您可以通过执行以下操作从 Animal 创建 Dog:

Dog newDog = new Dog(myExistingAnimal);
于 2009-06-11T17:41:42.250 回答
0

尝试使用工厂。与其基于构造函数,不如使用工厂根据您的约束返回特定类型的 Animal。

于 2009-06-12T09:57:53.963 回答
0

我不确定您到底想要什么,所以我假设您希望将 Animal 对象升级为 Dog 对象。

class AnimalImpl {
    // ...
}

class DogImpl extends AnimalImpl {
    // ...
}

class Animal {
    private AnimalImpl implementation;
    public Animal() {
        implementation = new AnimalImpl;
    }
    public void becomeADog() {
        implementation = new DogImpl(implementation);
    }
    // ...
}

像这样使用它:

Animal animal = getAnAnimalFromSomewhere();
// `animal` has generic Animal behaviour
animal.becomeADog();
// `animal` now has Dog behaviour

这可能不是您想要的,但是当一个对象应该具有完全不同的行为时,它会很有用,这取决于它的状态。

于 2009-06-12T10:13:49.073 回答
-1

你想继承 Animal 类吗?您还可以使用:

public class Dog extends Animal { 
    public Dog () {
        super();
        // other constructor stuff
    }
}

那么你的 Dog 对象就已经继承了属性。

于 2009-06-11T17:38:32.897 回答