方法本地类中的Java最终静态声明 [英] Java final static declarations in method local classes

查看:92
本文介绍了方法本地类中的Java最终静态声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在方法内声明局部内部类时,为什么包含最终的静态String或int是合法的,而包含其他对象却不合法?

When declaring a local inner class inside a method, why is it legal to include final static Strings or ints but not legal to include other objects?

例如:

class Outer {
void aMethod() {
    class Inner {
        final static String name = "compiles";
        final static int ctr = 10; // compiles
        final static Integer intThree = Integer.valueOf(3); // does not compile!
        final static obj objConst = new Object(); // does not compile!
    }

    Inner inner = new Inner();
}
}

编译时,我得到以下信息:

When I compile this, I get the following:

InnerExample.java:6: inner classes cannot have static declarations
        final static Integer outer = Integer.valueOf(3);
                             ^
InnerExample.java:7: inner classes cannot have static declarations
        final static Object objConst = new Object();
                            ^

为什么要区分?是因为String是不可变的吗?如果是这样,Integer.valueOf()也无效吗?

Why the distinction? Is it because String is immutable? If so, wouldn't Integer.valueOf() also be valid?

推荐答案

这是因为前两个静态成员被分配给原始类型或String类型的编译时常量.

It's because the first two static members are assigned to compile-time constants of primitive type or type String.

来自 Java语言规范,第8.1.3节:

8.1.3.内部类和封闭实例

8.1.3. Inner Classes and Enclosing Instances

内部类不能声明静态成员,除非它们是常量变量(第4.12.4节),否则会发生编译时错误.

Inner classes may not declare static members, unless they are constant variables (§4.12.4), or a compile-time error occurs.

并来自 4.12. 4 :

原始类型或String类型的变量是最终变量,并使用编译时常量表达式(第15.28节)进行了初始化,称为常量变量.

A variable of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28), is called a constant variable.

起初我发现这很令人惊讶.仔细考虑一下,此限制的一个优点是,无需担心何时初始化内部类的静态成员.您可以在包含类中移动内部类,而不必担心其静态成员的值将被更改.

I found this surprising at first. Thinking about it more, one advantage to this limitation is that there is no need to worry about when static members of inner classes are initialized. You can move an inner class around in its containing class, without concern that the values of its static members will be changed.

这篇关于方法本地类中的Java最终静态声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆