Home  >  Q&A  >  body text

java - Why are the member variables in the interface not constants?

switch (from) {
            case TAGs.casts://constant expression required
                break;
        }
        
//我的TAGs.casts是这样的
public interface TAGs {
    String casts = String.class.getSimpleName();
}

//如果写成这个样子就可以编译
public interface TAGs {
    String casts = "String";
}

Isn’t it said that the member variables in the interface are constants? Why can't I use the prompt to require constants on the case?

phpcn_u1582phpcn_u15822675 days ago816

reply all(4)I'll reply

  • 滿天的星座

    滿天的星座2017-06-23 09:15:11

    When using an interface, you must assign an initial value to the constant. If you write it yourself without giving an initial value, it must be wrong.

    reply
    0
  • 習慣沉默

    習慣沉默2017-06-23 09:15:11

    The case in switch needs to determine the value at compile time, and String.class.getSimpleName(); needs to be known at run time (although it is indeed a constant at run time), so the compilation cannot pass

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-06-23 09:15:11

    Indeed. One is required at compile time, and the other is runtime (reflection methods are all runtime). I answered it wrong before - when I looked at effective java, it was modified by static final. There is also a suggestion in it, please use enumeration class to export constants.

    reply
    0
  • 大家讲道理

    大家讲道理2017-06-23 09:15:11

    Didn’t it mean that the member variables in the interface are all constants? Where did you hear this sentence? Constants need to be modified with
    static final and need to be given an initial value

    reply
    0
  • Cancelreply