从父类对象调用子类方法
2022-09-01 21:46:30
我有以下课程
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在儿童中不常见)