gpt4 book ai didi

java - 我如何能够在类中引用实例的私有(private)字段?

转载 作者:行者123 更新时间:2023-11-29 10:11:58 24 4
gpt4 key购买 nike

我一直在寻找解释,但没能找到。为什么这段代码有效?具体来说——为什么可以访问实例的私有(private)成员?据我所知,只有在原始类中的方法中创建实例时,它才有效。

public class MyClass {
private int thing;

public MyClass () {}

public MyClass makeMe () {
MyClass myClass = new MyClass();
myClass.thing = 1;
return myClass;
}
}

最佳答案

私有(private)字段只能由该类访问。您仍在 MyClass 的实例中操作,因此您无需使用 setter 即可看到和访问私有(private)字段。

更正式一点... JLS 6.6.1谈论访问。

这是删节的片段,强调我的:

  • A member (class, interface, field, or method) of a reference (class, interface, or array) type or a constructor of a class type is accessible only if the type is accessible and the member or constructor is declared to permit access:

    • ...Otherwise, if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.

关于java - 我如何能够在类中引用实例的私有(private)字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30250486/

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