0

There's a pattern I've noticed in Java, and I was wondering if there's a name for it so I can look up implementations in other languages.

I've seen static final fields of a class used as method arguments. This limits the caller of the method to a public set of values for that argument. For example:

public class Calendar {

    public static final int JANUARY = 1;
    public static final int FEBRUARY = 1;
    //and so on

    public void setMonth(int month){
       //set month
    }
}

Calendar c = new Calendar();
c.setMonth(Calendar.JANUARY);

Is there a name for this pattern? Thanks...

(example edited to working code, been a long time since I wrote Java)

hypertext
  • 63
  • 1
  • 4

3 Answers3

6

Although your example is wrong, I think you are looking for enum

Suraj Chandran
  • 24,433
  • 12
  • 63
  • 94
  • 1
    Thank you. If any one else is looking for a PHP implementation, try [this](http://stackoverflow.com/questions/254514/php-and-enums). – hypertext Jun 27 '11 at 09:40
1
public class Calendar {

    public enum Month {
        JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER
    }

    private Month month;

    public void setMonth(Month month){
       this.month = month;
    }
}
oliholz
  • 7,447
  • 2
  • 43
  • 82
0

You shoud define enum

enum Month
{
Jan,Feb,Mar,Apr;
}
class Sample
{
public static void main(String arg[])
{
Month m=Month.Mar;
System.out.println(m); // Mar
}
}
Cris
  • 4,947
  • 6
  • 44
  • 73