gpt4 book ai didi

java - 一个类/多个构造函数与多个类(继承)

转载 作者:搜寻专家 更新时间:2023-11-01 03:50:40 25 4
gpt4 key购买 nike

目前我正在尝试实现以下树状结构(即 Man、Woman、Child、SpecialMan、SpecialWoman、SpecialChild)。有没有更简洁/替代(重复代码更少)的方法我可以接近它?

public class Person {
int hat;
int one_glove;
}

public class Man extends Person {
int coat;
int shorts;
}

public class Woman extends Person {
int coat;
}

public class Child extends Person {
int shorts;
}
public class SpecialMan extends Man {
int second_glove;
}

public class SpecialWoman extends Woman {
int second_glove;
}

public class SpecialChild extends Child {
int second_glove;
}

我在想的是让类 Person 包含所有变量,然后简单地为它设置多个构造函数 -> 链接到每个特定的对象类型?

public class Person{
int hat;
int one_glove;
int coat;
int shorts;
int second_glove;

public Person(int coat;int shorts; int hat; int one_glove;){} //Man
public Person(int coat;int hat; int one_glove;){} //Woman
public Person(int coat;int shorts; int hat; int one_glove; int second_glove;) {} //SpecialMan

etc...
}

最佳答案

您当前的方法是有意义的,并且遵循最佳实践,只保留与相关类中的每个类相关的变量(可能还有行为)。通过将它们都放在同一个类中,您最终会遇到一个对象可以访问它不需要的变量的情况。此外,在您提出的解决方案中,您可能最终会得到很多额外的代码来确定它是什么“类型”的人。例如。

if (coat != 0 && shorts == 0) {
// Do Child stuff
}

您可以在每个 Person 实例化时(可能使用枚举)为他们分配一个“类型”,但是您仍然需要在他们的行为不同的地方进行检查。您当前方法的优点是特定于类的行为仅限于它特定于的类,因此您永远不必进行此检查。如果一个 Child 有一个 play() 方法,你永远不需要在运行它之前检查你是否真的是一个 child 。

因此,虽然您可能会在当前方法中看到重复的代码,但它可能比您提出的解决方案要清晰得多。您可以通过谨慎使用 Interfaces 进一步提高代码的清晰度。 .

关于java - 一个类/多个构造函数与多个类(继承),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29634790/

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