【发布时间】:2012-07-13 01:34:17
【问题描述】:
我有以下课程
class Person {
private String name;
void getName(){...}}
class Student extends Person{
String class;
void getClass(){...}
}
class Teacher extends Person{
String experience;
void getExperience(){...}
}
这只是我实际架构的简化版本。最初我不知道需要创建的人的类型,因此处理这些对象的创建的函数将一般的Person 对象作为参数。
void calculate(Person p){...}
现在我想使用这个父类对象访问子类的方法。我还需要不时访问父类方法,所以我不能让它抽象。
我想我在上面的例子中简化了太多,所以这里是实际的结构。
class Question {
// private attributes
:
private QuestionOption option;
// getters and setters for private attributes
:
public QuestionOption getOption(){...}
}
class QuestionOption{
....
}
class ChoiceQuestionOption extends QuestionOption{
private boolean allowMultiple;
public boolean getMultiple(){...}
}
class Survey{
void renderSurvey(Question q) {
/*
Depending on the type of question (choice, dropdwn or other, I have to render
the question on the UI. The class that calls this doesnt have compile time
knowledge of the type of question that is going to be rendered. Each question
type has its own rendering function. If this is for choice , I need to access
its functions using q.
*/
if(q.getOption().getMultiple())
{...}
}
}
if 语句说“找不到 QuestionOption 的 getMultiple”。 OuestionOption 有更多的子类,它们有不同类型的方法,在子类中不常见(getMultiple 在子类中不常见)
【问题讨论】:
-
你有什么共同的抽象概念吗?您需要找到一种方法来表示联合概念中每个子类的细节。然后,您将能够在
Person中定义一个方法,您可以在具有适当行为的子类中覆盖该方法。 -
例如,你在计算什么?为什么不在每个子类中实现
calculate方法? -
calculate的 Person 参数是什么?如果这是计算的目标,也许它应该是calculate(),然后用this做一些事情(这对于覆盖子类中的方法非常有用)。 -
这个问题需要更多信息 - 它不完整。请准确说明您要执行的操作以及您看到的语法错误!
-
class是java中的保留字,Student的属性必须用别的名字
标签: java inheritance