小编use*_*663的帖子

从父类对象调用子类方法

我有以下课程

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

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

class Teacher extends Person{
    String experience;
    void getExperience(){...}
}
Run Code Online (Sandbox Code Playgroud)

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

void calculate(Person p){...}
Run Code Online (Sandbox Code Playgroud)

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


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

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) { …
Run Code Online (Sandbox Code Playgroud)

java inheritance

17
推荐指数
2
解决办法
8万
查看次数

标签 统计

inheritance ×1

java ×1