gpt4 book ai didi

java - 嵌套类有静态变量吗?

转载 作者:行者123 更新时间:2023-12-02 00:57:39 26 4
gpt4 key购买 nike

我知道嵌套类没有静态成员,

class OuterClass {
class InnerClass {
private static int x = 0; // this is error
}

}

但是当我们用final声明它时

 class OuterClass {
class InnerClass {
private static final int x = 0; // ok
}
}

这和final关键字有关吗,因为变量不能再改变了?或者还有其他原因吗?

最佳答案

此行为是 Java Language Specification 强制执行的:

8.1.3. Inner Classes and Enclosing Instances

An inner class is a nested class that is not explicitly or implicitly declared static.

An inner class may be a non-static member class (§8.5), a local class (§14.3), or an anonymous class (§15.9.5). A member class of an interface is implicitly static (§9.5) so is never considered to be an inner class.

It is a compile-time error if an inner class declares a static initializer (§8.7).

It is a compile-time error if an inner class declares a member that is explicitly or implicitly static, unless the member is a constant variable (§4.12.4).

An inner class may inherit static members that are not constant variables even though it cannot declare them.

A nested class that is not an inner class may declare static members freely, in accordance with the usual rules of the Java programming language.

Example 8.1.3-1. Inner Class Declarations and Static Members

class HasStatic {
static int j = 100;
}
class Outer {
class Inner extends HasStatic {
static final int x = 3; // OK: constant variable
static int y = 4; // Compile-time error: an inner class
}
static class NestedButNotInner{
static int z = 5; // OK: not an inner class
}
interface NeverInner {} // Interfaces are never inner
}

请注意,这已更改为 Java 16 :

All of the rules that apply to nested classes apply to inner classes. In particular, an inner class may declare and inherit static members (§8.2), and declare static initializers (§8.7), even though the inner class itself is not static.

关于java - 嵌套类有静态变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61139658/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com