1

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.

2
  • 1
    The statement HOMBRE("H"), MUJER("M"), OTRO("O") calls the constructors. Not your valueOf method. Commented Aug 18, 2018 at 0:33
  • thanks for the answer! Commented Aug 18, 2018 at 23:15

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@HectorEstigarribia If an answer helped you solve the issue, consider accepting it, thanks.
sorry.. i accepted the answer with the accept option, thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.