Why “final static int” can be used as a switch's case constant but not “final static

后端 未结 5 2108
遥遥无期
遥遥无期 2021-02-12 13:21

Why is this int switch valid:


public class Foo {
    private final static int ONE = 1;
    private final static int TWO = 2;

    public static void main(String         


        
5条回答
  •  旧时难觅i
    2021-02-12 13:47

    The case argument must be primitive; it cannot be an object.

    However, you can use enums as follows:

    RetentionPolicy value = ...
    switch (value) {
        case RUNTIME:
        case SOURCE:
    }
    

    Because value is declared to be of type RetentionPolicy you can use the enum constants directly inside the switch.

提交回复
热议问题