user1601401
user1601401

Reputation: 732

Getting which Enum Constant is called

Is there a way to call different methods for each constant in an Enum?

public enum ShipType {
   SMALL,MEDIUM,LARGE,ENORMOUS,TETRIS;

   public int[][] getRegionOfShip(int[] startingPosition, Aligment aligment){
      //How do can I decide which function to call?
   }
   private int[][] getRegionOfSmallShip(int[] startingPosition){
      ...
   }
   private int[][] getRegionOfMediumShip(int[] startingPosition, Aligment aligment){
      ...
   }

   private int[][] getRegionOfLargeShip(int[] startingPosition, Aligment aligment){
      ...
   }

   private int[][] getRegionOfEnourmusShip(int[] startingPosition, Aligment aligment){
      ...
   }

   private int[][] getRegionOfTetrisShip(int[] startingPosition, Aligment aligment){
      ...
   }
}

When I create the Enum like this:

ShipType shipType = ShipType.SMALL;

And I call it:

shipType.getRegionOfShip(startingPosition,aligment);

How can I make it, to call the

private int[][] getRegionOfSmallShip(int[] startingPosition)

method? Something like checking which Constant is called inside the Enum class

Upvotes: 2

Views: 81

Answers (2)

Alex - GlassEditor.com
Alex - GlassEditor.com

Reputation: 15557

Instead of creating a seperate method to call for each enum value you could just override the method:

public enum ShipType {
SMALL{
    @Override
    public int[][] getRegionOfShip(int[] startingPosition, Aligment aligment){

    }
},
MEDIUM{
    @Override
    public int[][] getRegionOfShip(int[] startingPosition, Aligment aligment){

    }
};
public abstract int[][] getRegionOfShip(int[] startingPosition, Aligment aligment);

If you choose this option you will avoid having to add a case to your ifs/switch when you add a new ship type, as well as not being able to forget to implement the method without a compile time error.

Upvotes: 4

Gilad Haimov
Gilad Haimov

Reputation: 5867

Java has no function pointers and creating a class hierarchy here will be over engineering, so just a switch:

public enum ShipType {
   SMALL,MEDIUM,LARGE,ENORMOUS,TETRIS;

   int[][] getRegionOfShip(startingPosition,aligment) {
       if (this == SMALL) {
           return  getRegionOfSmallShip(startingPosition)
       }
       else if (this == MEDIUM) {
           return  getRegionOfMediumShip(startingPosition);
       }
       etc.
   }
}

Upvotes: 0

Related Questions