【问题标题】:One Class/Multiple Constructors vs. Multiple Classes (Inheritance)一个类/多个构造函数与多个类(继承)
【发布时间】:2015-06-20 12:03:57
【问题描述】:

我目前正在尝试实现以下树状结构(即 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...
}

【问题讨论】:

  • 构造函数中的man 是什么?
  • 最好使用接口来指示附加字段的存在
  • 一个类/多个构造函数是什么意思?我的理解是一个具有多个构造函数的类。您至少可以澄清需要什么,并在可能的情况下提供样本。干杯!

标签: java inheritance interface multiple-inheritance


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案2】:

    简单地继承person类并使用super

    > public class Person{
     int hat;
     int one_glove;
     int coat;
     int shorts;
     int second_glove;
    
    public person(int a,int b,int c,int d,int e){
    hat  = a;
    one_glove = b;
    coat = c;
    shorts = d;
    second_glove = e;
    }
    
    }
    
    class man extends person(){
    
    man(int a,int b,int c,int d,int e){
    super(a,b,c,d,e);
    }
    }
    

    【讨论】:

      【解决方案3】:

      现在考虑使用方法的更简单示例:

      public class Animal{
          String name;
      
          void sleep() {
      
          }
      }
      
      public class Bird extends Animal {
          void whistle() {
      
          }
      }
      

      你现在怎么能只制作鸟哨而不让所有动物都发出没有继承的哨声。

      因此,如果您考虑拥有方法,那么您肯定想使用继承

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-09
        • 1970-01-01
        • 2011-07-06
        • 2015-01-17
        • 1970-01-01
        • 1970-01-01
        • 2022-10-17
        • 1970-01-01
        相关资源
        最近更新 更多