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

查看:34
本文介绍了为什么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天全站免登陆