Are enumerations allowed to have Java setters?

The question has already been answered. Thanks guys.

I have an enumeration and it has string parameters. Can I have setters for these variables?

public enum Blah {
    Monday("a"), Tuesday("b");
}

private final String letter;

Blah(String letter){
    this.letter = letter;
}

I am allowed to:

public String setLetter(String letter){
    this.letter = letter;
}
+9
source share
6 answers

You need to remove the modifier of finalthis field so that it can be set:

public enum Blah {
    Monday("a"), Tuesday("b");


    private String letter;

    private Blah(String letter){
        this.letter = letter;
    }

    public void setLetter(String letter){
        this.letter = letter;
    }
}

http://ideone.com/QAZHol

However, if an altered state in an enumeration is generally not recommended.

+11
source

This does not work because the field is marked as final.

In principle, there is nothing to protect the enumeration from mutable fields. However, this is rarely a good idea.

+3
source

: .

public class Main {

public enum Account {

    ACCOUNT("NAME");

    private String name;

    private Account(String name){
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

public static void main(String[] args) {
    System.out.println(Account.ACCOUNT.getName()); // print NAME
    Account.ACCOUNT.setName("NEW");
    System.out.println(Account.ACCOUNT.getName()); // print NEW
}

}

+3

Enums final.
, - .

:
Enums, , NonChanging/FIXED .

+1
public class EnumExample {
        public enum Blah {
        Monday("a"), Tuesday("b");


        private String letter;

        private Blah(String letter){
            this.letter = letter;
        }

        public void setLetter(String letter){
            this.letter = letter;
        }

        public String getLetter(){
             return letter;
        }
    }

        public static void main (String[] args)         {
             System.out.println("The Value of Monday is "+ Blah.Monday.getLetter());//prints a
             System.out.println("The Value of Tuesday is "+Blah.Tuesday.getLetter());//prints b
        }
}
0

, , enum , , , , Java, , , Java ( , enum, ), .

, OP volatile (, final):

volatile int letter;

In more complex cases, such as the increment or the other (very unlikely to transfers, but ... who knows installer transfers itself is exotic), other weapons of parallelism, such as blocks Atomic, synchronized, Lockmay be necessary.

In addition, there is a discussion of the security of enumerated streams.

0
source

All Articles