为什么Java禁止内部类中的静态字段? [英] Why does Java prohibit static fields in inner classes?

查看:186
本文介绍了为什么Java禁止内部类中的静态字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class OuterClass {
 class InnerClass {
  static int i = 100; // compile error
  static void f() { } // compile error
 }
} 

虽然无法使用 OuterClass.InnerClass.i 访问静态字段,但如果我想记录应该是静态的内容,例如创建的InnerClass对象的数量,使该字段静态是有帮助的。所以为什么 Java禁止内部类中的静态字段/方法?

Although it's not possible to access the static field with OuterClass.InnerClass.i, if I want to record something that should be static, e.g. the number of InnerClass objects created, it would be helpful to make that field static. So why does Java prohibit static fields/methods in inner classes?

编辑:我知道如何使编译器满意静态嵌套类(或静态内部类),但我想知道的是为什么java禁止语言设计和实现方面内部类(或普通内部类)内的静态字段/方法,如果有人知道更多。

I know how to make the compiler happy with static nested class (or static inner class), but what I want to know is why java forbids static fields/methods inside inner classes (or ordinary inner class) from both the language design and implementation aspects, if someone knows more about it.

推荐答案

内部类背后的想法是在封闭实例的上下文中操作。不知何故,允许静态变量和方法与这种动机相矛盾?

The idea behind inner classes is to operate in the context of the enclosing instance. Somehow, allowing static variables and methods contradicts this motivation?


8.1.2内部类和封闭实例

8.1.2 Inner Classes and Enclosing Instances

内部类是未显式或隐式声明为静态的嵌套类。内部类可能不会声明静态初始化器(第8.7节)或成员接口。内部类可能不会声明静态成员,除非它们是编译时常量字段(第15.28节)。

An inner class is a nested class that is not explicitly or implicitly declared static. Inner classes may not declare static initializers (§8.7) or member interfaces. Inner classes may not declare static members, unless they are compile-time constant fields (§15.28).

这篇关于为什么Java禁止内部类中的静态字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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