【发布时间】: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