我有以下课程
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 在子类中不常见)
原文由 user1349663 发布,翻译遵循 CC BY-SA 4.0 许可协议
注意: 虽然这是可能的,但完全不推荐这样做,因为它会破坏继承的原因。最好的方法是重构您的应用程序设计,以便 没有父子 依赖关系。父母永远不需要知道孩子或他们的能力。
但是..你应该能够这样做:
一个安全的方法是: