我有以下课程
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 在子类中不常见)