gpt4 book ai didi

java - 除非用常量表达式初始化,否则不能在非静态内部类型中将字段声明为静态

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:20:16 27 4
gpt4 key购买 nike

public class Test {

public enum Directions {
NORTH, WEST, SOUTH, EAST
}

static final Directions D1 = Directions.NORTH;

static class Inner {
static final Directions D2 = Directions.NORTH;
}

class Inner2 {
static final Directions D3 = Directions.NORTH;
}

}

我收到标题中的 IDE 错误,指的是变量 D3。有人可以向我解释一下吗?为什么我不能在非静态的内部类中声明静态变量,为什么枚举值不是常量?

最佳答案

JLS §8.1.3 Inner Classes and Enclosing Instances

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


Why is an Enum entry not considered a constant variable?

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.

关于java - 除非用常量表达式初始化,否则不能在非静态内部类型中将字段声明为静态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37509919/

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