我有以下的类
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方法”。QuestionOption有许多子类,这些子类具有不同类型的方法,这些方法在子类之间不是通用的(getMultiple不是子类之间共有的方法)
Person
中定义一个方法,在子类中覆盖它并实现适当的行为。 - Marko Topolnikcalculate
方法? - Marko Topolnikcalculate
函数中的 Person 参数是什么意思?如果它是计算的目标,也许应该改成calculate()
,然后使用this
做一些操作(这将与子类中的重写方法很好地配合)。 - Thilo