有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java访问私有字段而不使用getter方法?

以下是JDK7源代码的摘录:

public String(String original) {
    this.value = original.value;
    this.hash = original.hash;
}

valuehash都是private字段。为什么original.value是合法的


共 (6) 个答案

  1. # 1 楼答案

    访问修饰符描述对类的访问,而不是对实例的访问。由于value是在String类中声明的,因此它的所有成员(如构造函数)都可以无限访问它

  2. # 2 楼答案

    您应该查看访问控制表

    Modifier    Class   Package Subclass    World
    ---------------------------------------------
    
    private     **Y**      N        N           N
    

    http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

    The private modifier specifies that the member can only be accessed in its own class.

    因为它在类中,所以您可以访问它

  3. # 3 楼答案

    类可以访问自己的私有字段(即使在this以外的其他实例上)

  4. # 4 楼答案

    this table

                       Access Levels
    Modifier     | Class  | Package   |  Subclass | World
    -------------+--------+-----------+-----------+--------
    public       |   Y    |     Y     |     Y     |   Y
    protected    |   Y    |     Y     |     Y     |   N
    no modifier  |   Y    |     Y     |     N     |   N
    private      |   Y  ← |     N     |     N     |   N    
    
  5. # 5 楼答案

    getter和setter实际上用于类范围之外的实现。 在一个类中,任何变量都可以不受任何限制地访问

  6. # 6 楼答案

    Both value and hash are private filed. Why is original.value legal?
    

    因为它仍然在String类中,并且可以使用同一个类访问私有变量