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
    }
}
1
  • 1
    then just initialize it in your default Commented Apr 9, 2013 at 9:10

4 Answers 4

4

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

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

Comments

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

3 Comments

You can assign value of a final variable inside constructor
You don't have to initialise a final variable at the point of declaration: en.wikipedia.org/wiki/Final_(Java)#Final_variables
Ok :) I learned something.
0

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

assert (foo = 0) > 0 : "missing TYPE detected";

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.