最终变量的可访问性
为什么不能在静态变量中访问 Final 变量。 在编译时,它们只是简单地替换为直接替换为它们的值 所以,即使在静态方法中也应该允许它们使用,
为什么有这个限制???
Why can't Final variables be accessed in a static variables.
At the compile time they are simply substituted directly substituted with their values
so, they should be allowed to use even in static methods
why is this restriction???
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
静态 = 在类中。
Final = 不会改变它的值(但如果它不是静态的,它就是每个实例的值)。
例如,您可以这样做:
每次创建 Weird 对象时,它都会包含不同的创建值。
但 Weird.number 的值将是类加载的时间。
static = in the class.
final = doesn't change it's value (but it is of each instance if it's not static).
By examply you can do:
Each time you create a Weird object it will contain a different value for created.
But the value of Weird.number will be the time when the class was loaded.
并非所有
final
变量都是编译时常量。只有静态最终变量可以被编译器替换为编译时常量。final
修饰符在某些情况下仅用于确保 const-正确性。并且静态方法无法访问非静态变量,因为这些变量对于同一类的不同实例可以具有不同的值。
Not all
final
variables are compile time constants. Onlystatic final
variables can be substituted by compiler as compile-time constants.final
modifier in certain cases is only used to ensure const-correctness.And
static
methods cannot access non-static variables as those variables can have different values for different instances of the same class.如果您问为什么
static
方法无法访问final
实例变量(基于 [错误] 的假设,即最终成员变量始终设置为常量值代码),这是因为同一个final
实例变量(例如可以通过构造函数设置)可以有不同的值。静态方法不知道类的任何特定实例,只能访问静态最终变量。If you're asking why a
static
method cannot access afinal
instance variable (on the [incorrect] assumption that final member variables are always set to literal or constant values in the code), its because different instances of a class can have different values for the samefinal
instance variable (which can be set, for example, via the constructor). Astatic
method has no knowledge of any particular instance of the class, and could only accessstatic final
variables.