java - Why are the member variables in the interface not constants?
phpcn_u1582
phpcn_u1582 2017-06-23 09:13:11
0
4
812
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_u1582
phpcn_u1582

reply all(4)
滿天的星座

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.

習慣沉默

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

过去多啦不再A梦

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.

大家讲道理

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!