gpt4 book ai didi

java - 具有额外属性的子类构造函数

转载 作者:行者123 更新时间:2023-12-02 04:55:20 31 4
gpt4 key购买 nike

如果我有一个类“Dog”,它扩展了另一个类“Animal”,并且 Animal 类有一个带有多个属性(如 latinName、latinFamily 等)的构造函数。我应该如何为狗创建构造函数?我是否应该包含在 Animal 中找到的所有属性以及 Dog 中我想要的所有额外属性,如下所示:

public Animal(String latinName){
this.latinName = latinName;
}

public Dog(String latinName, breed){
super(latinName);
this.breed = breed;
}

实际的类具有比我在这里列出的更多的属性,因此狗的构造函数变得相当长,并且让我怀疑这是否是正确的方法或者是否有更简洁的方法?

最佳答案

Should I include all attributes that are found in Animal...

那些对狗来说不是不变的,是的(不管怎样;见下文)。但例如,如果 AnimallatinFamily,那么您不需要 Dog 也有它,因为它总是 “犬科动物”。例如:

public Animal(String latinFamily){
this.latinFamily = latinFamily;
}

public Dog(String breed){
super("Canidae");
this.breed = breed;
}

如果您发现构造函数的参数数量不合适,您可以考虑构建器模式:

public class Dog {

public Dog(String a, String b, String c) {
super("Canidae");
// ...
}

public static class Builder {
private String a;
private String b;
private String c;

public Builder() {
this.a = null;
this.b = null;
this.c = null;
}

public Builder withA(String a) {
this.a = a;
return this;
}

public Builder withB(String b) {
this.b = b;
return this;
}

public Builder withC(String c) {
this.c = c;
return this;
}

public Dog build() {
if (this.a == null || this.b == null || this.c == null) {
throw new InvalidStateException();
}

return new Dog(this.a, this.b, this.c);
}
}
}

用法:

Dog dog = Dog.Builder()
.withA("value for a")
.withB("value for b")
.withC("value for c")
.build();

这使得更容易清楚哪个参数是哪个,而不是构造函数的一长串参数。您可以获得清晰的好处(您知道 withA 指定“a”信息,withB 指定“b”等),但没有一半的危险-构建 Dog 实例(因为部分构建的实例是不好的做法); Dog.Builder 存储信息,然后 build 执行构造 Dog 的工作。

关于java - 具有额外属性的子类构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28828666/

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