vendredi 16 avril 2021

Marker Interface VS Enum Type

Suppose I have an Animal abstract class, with subclasses Tiger, Wolf, Parrot, Eagle, Shark and Dolphin.

If I want to distinguish different animal types, say terrestrial, aerial and aquatic animals, would it be better to use a marker interface or use an enum class? For example

public interface TerrestrialAnimal{}
public abstract class Animal{}

public class Wolf extends Animal implements TerrestrialAnimal{}

Or with the enums

public enum AnimalType{
  Terrestrial, Aquatic, Aerial
}

public abstract class Animal{
  private final AnimalType type;

  public Animal(AnimalType type){
  this.type = type;
  }
}

public class Wolf extends Animal{
  public wolf{
    super(EnumType.getTerrestrial)
  }
}

What are the pros and cons of each design? One downside I see from the interface is that it creates three extra files. Thanks!

Aucun commentaire:

Enregistrer un commentaire