子接口如何重用其父项的实现?

gst*_*low 8 java inheritance implementation interface composition

最近我接受了一次采访,我被问到以下问题.给定以下类/接口结构:

在此输入图像描述

题:

如何实现接口EmployedStudent来重用代码StudentImplEmployeeImpl.

我建议将员工和学生组成我的实施.

根据采访者的反应,我不认为他们认为这是最好的解决方案.我花了很多时间思考它,但我无法想出另一个解决方案.

use*_*038 5

创建一个实现两者Employee和的类Student.在您的班级中,创建两个EmployeeImpl和的实例StudentImpl.使您的类将所有方法调用委托给其中一个对象.

public class EmployedStudent implements Employee, Student {

  private EmployeeImpl employee = new EmployeeImpl();
  private StudentImpl student = new StudentImpl();

  public int getSalary() {
    return this.employee.getSalary();
  }

  public float getAverageGrade() {
    return this.student.getAverageGrade();
  }

}
Run Code Online (Sandbox Code Playgroud)

  • @meister_reineke:通过委托,你实际上*将*使用``EmployeeImpl``和``StudentImpl``类的现有代码. (2认同)

glg*_*lgl 1

由于java不支持多重继承,你可以/应该

  • 要么为每个想要的超类都有一个字段
  • 或者从一个超类派生并拥有另一个超类的字段。

然后,这些字段由相应方法的“我们的”实现引用。

这是来自GoF的设计模式之一,我认为是Proxy模式