Java – Composition of Classes Implementing the Same Interface

compositioninterfacesjava

Let's consider an example wherein I have to model the following:

  1. Class to schedule exams for a Student, lets call it StudentExamScheduler
  2. Class to schedule exam for a Class. Let's call it ClassExamScheduler and currently it depends on the logic provided by StudentExamScheduler.

So since both the classes schedule exams, I created an interface ExamScheduler which both the classes would implement. Reason being:

  • They are essentially scheduling exams
  • would give me the flexibility to swap the schedulers in-and-out as functionality changes.

This is how the interface would look:

interface ExamScheduler {
       scheduleExam(data);
}

Now each of my concrete class implements this interface and ClassExamScheduler now uses the StudentExamScheduler to delegate some responsibilities.

class ClassExamScheduler implements ExamScheduler {

  private ExamScheduler studentExamScheduler;

  public scheduleExam() {

    studentExamScheduler.scheduleExam();
    // do other stuff
  }
}

Is this a valid use of Interface & Composition? Typically I have seen Interface being used for polymorphism. But in this use case I use it to provide me flexibility to inject new classes when the requirements change.

Best Answer

My two cents:

  • There's no contradiction between the use of interfaces and composition.
  • You are using polymorphism. Dependency injection and delegation are possible because of polymorphism.

A couple of observations:

  • The studentExamScheduler should be named examScheduler. Since you will be injecting it you should not name the variable after an specific implementos of ExamScheduler.
  • Consider creating a more generic Scheduler interface, with a schedule(ScheduleData data); such an interface could be implemented by any type of scheduler like LessonScheduler, MeetingScheduler etc.
Related Topic