为什么内部类不能使用静态初始化器? [英] Why can't an inner class use static initializer?

查看:199
本文介绍了为什么内部类不能使用静态初始化器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Quoth JLS#8.1 .3 :

内部类不能声明静态初始化程序(

Inner classes may not declare static initializers (§8.7)......

这是这样证明的:

class A {
    class B {
        static { // Compile-time Error: Cannot define static initializer in inner type A.B
            System.out.println("Class is initializing...");
        }
    }
}

现在,因为Java的内部(非静态)类由类加载器,为什么我们不能为它们提供静态初始化器?

Now since Java's inner (non-static) classes are loaded by class loaders just like every other class, why can't we have static initializers for them?

此限制背后的原因是什么?

推荐答案

无效使用

只是我的观点,对论据/辩论表示赞赏

请阅读以下主题.

这说明了为什么Java为什么禁止内部类中的静态字段

IMO同样的原因也适用于static initializer.毕竟,造成问题的是关键字static.

IMO the same reason also applied to static initializer. After all, the thing that creating problem is the keyword static.

除了上述线程中说明的原因外,我还可以给出另一个 lam原因> .
static initializer的名称为我们提供了有关何时以及为何使用此块的提示.人们不只是使用静态初始化程序块来打印hello world [在此处插入模因].
使用此块的主要原因显然是要初始化静态变量.

Added to the reason explained in above thread, I can give another lame reason.
The name of the block static initializer give us a hint on when and why to use this block. One does not simply use static initializer block to print hello world [insert the meme here].
The main reason to use this block is clearly to initialize static variable.

现在,由于内部类/非静态嵌套类不允许使用静态变量,因此允许使用静态初始化程序有什么意义?

Now as inner class/ non-static nested class don't allow static variable, what is the point of allowing static initializer?

这篇关于为什么内部类不能使用静态初始化器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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