1

I want to initialize a final field in different ways. Therefore I have created an enumeration type and perform a switch over it.

    public enum TYPE {
        A,
        B,
    }

I have also added a default case to the switch with an assertion to warn my fellow programmers in case they add a new enumeration constant and forget to update the switch.

        default:
            assert false : "missing TYPE detected";

Java however detects the flaw in my argument and complains that the blank field may not have been initialized. How should I deal with this situation?

public class SwitchExample
{
    public enum TYPE {
        A,
        B,
    }

    private final int foo;

    public SwitchExample(TYPE t)
    {
        switch (t) {
        case A:
            foo = 11;
            break;

        case B:
            foo = 22;
            break;

        default:
            assert false : "missing TYPE detected";
        }

        // The blank final field foo may not have been initialized
    }
}
Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137

4 Answers4

4

Instead of the assert false : "missing TYPE detected"; you may throw an IllegalArgumentException("missing TYPE detected")

Xavier Delamotte
  • 3,519
  • 19
  • 30
0

As you re-assign foo reference

foo = 11;

you cannot declare it as final

private final int foo;

See http://javarevisited.blogspot.fr/2011/12/final-variable-method-class-java.html

Gab
  • 7,869
  • 4
  • 37
  • 68
0

You can change code after your default to something like this:

assert (foo = 0) > 0 : "missing TYPE detected";
Dmitry Zaytsev
  • 23,650
  • 14
  • 92
  • 146
0

If using the final keyword you are forced to set its value in all cases in your switch statement. To get around this, just set your foo to a value you know means that an error has occured e.g. -1

maloney
  • 1,633
  • 3
  • 26
  • 49