Jonas
Jonas

Reputation: 7875

Defining the Type of List in the subclass

I have an abstract class Workout and the classes WorkoutCircuit and WorkoutSNR that inherit from Workout.

Also I have the abstract class Exercise and the classes ExerciseCircuit and ExerciseSNR that inherit form Exercise.

The class Workout has an ArrayList<Exercise> exercises, with the corresponding getter and setter methods. Now I want to be able to call getExercises() on an Object of WorkoutCircuit and get an ArrayList<ExerciseCircuit> back and vice versa for WorkoutSNR.

I haven´t figured out how to do this because I can't override the getExercises() method in the subclasses and case ArrayList<Exercise> into ArrayList<ExerciseCurcuit>

Upvotes: 3

Views: 139

Answers (1)

davidxxx
davidxxx

Reputation: 131346

It is a good case to make Workout a generic class in order to allow subclass to define the type of element of the List returned by getExercises().
Generic classes allows the parametric polymorphism, which is what you are looking for.
You could define Workout like :

public abstract class Workout<T extends Exercise>{

   private List<T> exercises;
   public List<T> getExercises(){
      return exercices;
   }
   ...
}

And the subclasses could be :

public class WorkoutCircuit extends Workout<ExerciseCircuit>{
   ...     
}

and :

public class WorkoutSNR extends Workout<ExerciseSNR>{
   ...     
}

Note that the use of a bounded type parameter (class Workout<T extends Exercise) is not mandatory. For example class Workout<T> would be legal and it would mean that any type is accepted for the subclasses.
But specifying a more precise type provides two advantages :

  • it allows to restrict the possible types that the subclass could use.
  • it allows the abstract class to manipulate a specific declared type : Exercice instead of Object. Which could be helpful if the class provides some processing on the list using specific methods of Exercice.

Upvotes: 5

Related Questions