从父类对象调用子类方法

新手上路,请多包涵

我有以下课程

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 许可协议

阅读 649
2 个回答

注意: 虽然这是可能的,但完全不推荐这样做,因为它会破坏继承的原因。最好的方法是重构您的应用程序设计,以便 没有父子 依赖关系。父母永远不需要知道孩子或他们的能力。

但是..你应该能够这样做:

 void calculate(Person p) {
    ((Student)p).method();
}

一个安全的方法是:

 void calculate(Person p) {
    if(p instanceof Student) ((Student)p).method();
}

原文由 techfoobar 发布,翻译遵循 CC BY-SA 3.0 许可协议

父类不应该知道子类。您可以实现一个方法 calculate() 并在每个子类中覆盖它:

 class Person {
    String name;
    void getName(){...}
    void calculate();
}

接着

class Student extends Person{
    String class;
    void getClass(){...}

    @Override
    void calculate() {
        // do something with a Student
    }
}

class Teacher extends Person{
    String experience;
    void getExperience(){...}

    @Override
    void calculate() {
        // do something with a Teacher
    }

}

顺便一提。您关于抽象类的陈述令人困惑。您可以调用抽象类中定义的方法,但当然只能调用子类的实例。

In your example you can make Person abstract and the use getName() on instanced of Student and Teacher .

原文由 Matteo 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题