Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

363
Visualizações
Number in parentheses after enum instance

I am reading a book on programming and I met such thing:

public static enum Month {
JANUARY(1),
FEBRUARY(2),
MARCH(3),
APRIL(4),
MAY(5),
JUNE(6),
JULY(7),
AUGUST(8),
SEPTEMBER(9),
OCTOBER(10),
NOVEMBER(11),
DECEMBER(12);
Month(int index) {
this.index = index;
}

What does a number in parentheses mean after an enum instance? Is it an enum constructor?

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

What does a number in parentheses mean after an enum instance? Is it an enum constructor?

JANUARY(1), FEBRUARY(2), etc... are indeed enum constructors.

But a number is not necessary required to specify a constructor in an enum. Here you have a number but it could be anything else and it could also have as many arguments as required.

Note that actually the enum declaration misses the index field and could not compile.
It would be correct :

public static enum Month {
    JANUARY(1),
    FEBRUARY(2),
    MARCH(3),
    APRIL(4),
    MAY(5),
    JUNE(6),
    JULY(7),
    AUGUST(8),
    SEPTEMBER(9),
    OCTOBER(10),
    NOVEMBER(11),
    DECEMBER(12);

    private int index;

    Month(int index) {
        this.index = index;
    }
}

I would add that an enum is above all a class. So each enum values (here JANUARY, FEBRUARY, ...) will be instantiated by invoking the class constructor.
And as for any class, as you don't define a constructor the compiler will generate a default with no arg.
So it is valid :

public static enum Fruit {
    APPLE(),
    ORANGE();       

    Fruit() {
    }
}

That is also valid :

public static enum Fruit {
    APPLE(),
    ORANGE();       
}

But for enums with no arg in the constructor, we generally use this convenient syntax reserved for enums :

public static enum Fruit {
    APPLE,  // with no parenthesis
    ORANGE; // with no parenthesis  
}
about 4 years ago · Santiago Trujillo Relatório

0

This is the constructor being invoked by every enum value:

Month(int index) {
this.index = index;
}
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda