gpt4 book ai didi

java - 为什么在方法中定义的类中使用访问修饰符

转载 作者:行者123 更新时间:2023-11-30 03:27:16 24 4
gpt4 key购买 nike

在方法内部定义的类的字段上使用访问修饰符有什么意义?

例如:

class Outer
{
public static void main (String[] args)
{
// class defined inside method
class Test
{
// applies an access modifier
public int field;
}

Test test = new Test();
}
}

我的以下两个陈述是否正确:

  • 无论访问修饰符如何,从该方法范围之外访问该字段的唯一方法仍然是使用反射
  • 无论访问修饰符如何,始终可以在方法的范围内访问该字段,即使该字段是私有(private)的,也无需任何反射。

令我印象深刻的是,虽然不可能对类使用访问修饰符,但它完全适用于其成员。尽管它们对我来说似乎都没有意义。

最佳答案

Regardless of the access modifier, still the only way to access the field from outside the scope of this method, is using reflection.

正确。但是,如果您遇到此问题,那么该类确实不应该是本地类。

Regardless of the access modifier, the field can always be accessed inside the scope of the method, even when the field is private without any need of reflection.

本地类的用例很少而且相距甚远。访问修饰符实际上没有任何影响,因为您的类应该是创建它的方法的本地类:

Like member classes, local classes are associated with a containing instance, and can access any members, including private members, of the containing class.

http://docstore.mik.ua/orelly/java-ent/jnut/ch03_11.htm

编辑:

编译器允许您指定一个修饰符,但它并不强制执行,这似乎很奇怪。我可以想到为什么会出现这种情况的两个很好的理由:

  1. 无论类(class)范围如何,都有标准的类(class)格式。
  2. 它允许您显示您打算如何访问成员,访问私有(private)字段/方法可能是一个坏主意,即使这样做在语法上没有错误。

关于java - 为什么在方法中定义的类中使用访问修饰符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29894349/

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