Hector Estigarribia
Hector Estigarribia

Reputation: 21

Why the java method Enum.valueof invoke the enum type constructor?

I have built this kind of data enum:

enum Sexo {
    HOMBRE("H"), MUJER("M"), OTRO("O"); 
    private String sexo;        
    private Sexo(String sexo){ 
        System.out.println("constructor del tipo enum");
        this.sexo=sexo;
    }
 }

Then, in the Main method i just do this:

public static void main(String[] args) {

    Sexo sexo1 = Enum.valueOf(Sexo.class, "HOMBRE"); 
    Sexo sexo2 = Enum.valueOf(Sexo.class, "MUJER"); 
    Sexo.valueOf("OTRO");

}

then, i have this on the console:

constructor del tipo enum
constructor del tipo enum
constructor del tipo enum

i understand that i have a call to the constructor for each enum type whit the sentence "Sexo" (name of the enum type). But: why the constructor is running just once? note that i have two instances and one direct call to the class.

Upvotes: 1

Views: 135

Answers (1)

k5_
k5_

Reputation: 5568

It isnt the method valueOf that calls the constructor.

The constructor of an enum is called for every literal when the class is first used. So in your case thats before the first call to Enum.valueOf.

The three calls to the constructor are caused by the three literals not your three calls to valueOf.

Upvotes: 3

Related Questions