“Sets” of a particular enum type but with generics

后端 未结 4 1977
北荒
北荒 2021-01-31 16:24

Let\'s say I have an abstract class

public abstract class Trainer{}

I have specific trainers like :

pub         


        
4条回答
  •  鱼传尺愫
    2021-01-31 16:46

    Yes you can move your Trainables , Set completed and trainingComplete(Trainables t) to the class Trainer.

    This way you no need to write these code each DogTrainer, HorseTrainer .. and so on...

     abstract class Trainer{
         public enum Trainables implements TrainingActions{
                BARK, BITE, ROLLOVER, FETCH;
         }
          public Set completed = new HashSet();
          public void trainingComplete(Trainables t){completed.add(t);}
    }
    

    Otherwise make trainingComplete(Trainables t) abstract and you need to implement in each Trainer implementaion clasees.

    abstract class Trainer{
         public enum Trainables implements TrainingActions{
                BARK, BITE, ROLLOVER, FETCH;
         }
          public Set completed = new HashSet();
          abstract public void trainingComplete(Trainables t);
    }
    

    Now your DogTrainer and HorseTrainer are implementing trainingComplete(Trainables t)

     public class DogTrainer extends Trainer{      
         public void trainingComplete(Trainables t){
              completed.add(t);
         }
     }
    
     public class HorseTrainer extends Trainer{     
         public void trainingComplete(Trainables t){
               completed.add(t);
         }
     }
    

提交回复
热议问题