同一类的对象(实例)之间的可访问性

时间:2018-03-31 10:03:05

标签: java

  

当一个类的一个对象具有对另一个对象的引用时   在同一个类中,第一个对象可以访问所有第二个对象   数据和方法(包括那些私有的)。

我从一本书中拿了这句话。但我无法弄清楚它的含义。

4 个答案:

答案 0 :(得分:2)

这意味着私有成员对同一个类的其他实例可见。例如:

class A {
  private int v;

  public boolean isSameV(A other) {
    return this.v == other.v; // can acccess other.v
  }
}

答案 1 :(得分:1)

实际上很好的问题,当我开始学习Java时,我遇到了类似的问题,这是它在实践中的表现:

public class A {

    private String example;
    protected int anotherOne;

    public A(){

    }

    public A(A a){
        this.example = a.example; // here we get access to private member of another object of same class
        this.anotherOne = a.anotherOne; // it works for protected as well
    }

    // This works for methods not just constructor, lets consider we want to swap value of example:
    public void swapExample(A a){
        String temp = a.example;
        a.example = this.example;
        this.example = temp;
    } 

} 

答案 2 :(得分:1)

可以从类内部访问

Private个字段,通过这种结构,您可以在课堂Foo中访问Foo实例的所有字段而无需getter和setter :

public class Foo {

    private String name;

    public int sumLetter(Foo b) {
        return this.name.length() + b.name.length();
    }
}

文档:Declaring Member Variables

  • 私有修饰符 - 该字段只能在自己的类中访问。

答案 3 :(得分:1)

这意味着如果你有一个看起来像这样的课程

public class A {
    private int number;
    private A otherInstance;

    public int number2;

    public void DoStuff() {
        ...
    }    
}

您可以使用A.number方法(或任何其他类方法)访问DoStuff,即使number实际上是private

e.g。

public class A {
    ...
    public void DoStuff() {
        this.otherInstance.number = 42;
                          ^^^^^^^
                  cannot access private members here
    }
}

非常好,而

public class B {
    private A aInstance;

    public void DoStuffToo() {
        this.aInstance.number = 42;
    }
}

无法编译,因为B无法访问A的私人成员。

相关问题