从父类对象调用子类方法 [英] Call a child class method from a parent class object

查看:270
本文介绍了从父类对象调用子类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程

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

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

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

这只是我的实际架构的简化版本。最初我不知道需要创建的人的类型,因此处理这些对象的创建的函数将通用 Person 对象作为参数。

This is just a simplified version of my actual schema. Initially I don't know the type of person that needs to be created, so the function that handles the creation of these objects takes the general Person object as a parameter.

void calculate(Person p){...}

现在我想使用这个父类对象访问子类的方法。我还需要不时访问父类方法,所以我不能使它抽象

Now I want to access the methods of the child classes using this parent class object. I also need to access parent class methods from time to time so I CANNOT MAKE IT ABSTRACT.

我想我在上面的例子中简化得太多了,所以这就是实际的结构。

I guess I simplified too much in the above example, so here goes , this is the actual structure.

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在子节点中不常见)

The if statement says "cannot find getMultiple for QuestionOption." OuestionOption has many more child classes that have different types of methods that are not common among the children (getMultiple is not common among the children)

推荐答案

注意: 虽然这是po可以,它完全没有被推荐,因为它破坏了继承的原因。最好的方法是重新构建应用程序设计,以便有 NO 父对象依赖项。父母不应该知道自己的孩子或他们的能力。

NOTE: Though this is possible, it is not at all recommended as it kind of destroys the reason for inheritance. The best way would be to restructure your application design so that there are NO parent to child dependencies. A parent should not ever need to know its children or their capabilities.

然而..你应该能够这样做:

However.. you should be able to do it like:

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

安全的方式是:

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

这篇关于从父类对象调用子类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆