有 Java 编程相关的问题?

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

java对私有访问修饰符的澄清

我正在试用Ivor Horton的Java书中的以下代码,其中一个二维点是通过一个简单的类实现的

public class Point
{
  //x and y coordinates
  private xVal,yVal;
  //Constructor
  public Point (double x, double y)
  {
    this.xVal = x;
    this.yVal = y;
  }
  //Constructor
  public Point (final Point aPoint)
  {
    this.xVal = aPoint.xVal;
    this.yVal = aPoint.yVal;

  }

}

现在,我不明白的是,在第二个构造函数中,将point类型的对象作为参数,新创建的point对象可以直接访问参数point对象的实例变量x和y。这意味着,除了同一类中的方法外,还可以从同一类型的另一个对象的方法内部访问对象的私有成员(方法和变量)。任何人都可以澄清这个问题,因为根据我的理解,Arumment对象的变量应该通过getter和setter访问,因为它们是私有的


共 (6) 个答案

  1. # 1 楼答案

    javadocs

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

    你可以在任何地方访问类的私有成员,包括构造函数

  2. # 2 楼答案

    这是一种常见的误解,即只有同一实例才能访问私有字段

    实际上,私有字段在该类中是私有的,而不是实例。所以该类的任何实例在该类中都可以访问私有字段

    JLS - Section 6.6.1

    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.

    我的

  3. # 3 楼答案

    注意,访问限制的目的是明确代码部分之间耦合的范围和范围

    从这个角度来看,类/实例的私有成员应该可以被该类声明中包含的所有代码访问,实际上它们是可以访问的

  4. # 5 楼答案

    This means that private members(methods and variables) of an object can be accessed from inside methods of another object of the same type

    是的,这是正确的。“私有”访问修饰符在文件级工作

    这意味着,如果一个类是另一个的嵌套(静态或非静态)、本地或匿名类,并且您拥有另一个类的有效对象引用(显式或隐式),那么您不仅可以从不同的对象访问私有成员,甚至可以从不同的类访问私有成员。这在两个方向上都有效(外部<;->;内部)

  5. # 6 楼答案

    首先,代码中有一个错误。 应该是:

    public class Point
    {
      //x and y coordinates
      private xVal,yVal;
      //Constructor
      public Point (double x, double y)
      {
        this.xVal = x;
        this.yVal = y;
      }
      //Constructor
      public Point (final Point aPoint)
      {
        this.xVal = aPoint.xVal;
        this.yVal = aPoint.yVal;
      }
    }
    

    注意第二个C'tor点变量

    其次,private表示对类私有。事实并非如此。 因此,该类的其他实例可以访问私有成员/方法