-2
class TestPrivate2 {
private int n;
}

public class TestPrivate {

private int n;

public void accessOtherPrivate(TestPrivate other) {
    other.n = 10;// can use other class's private field,why??????????
    System.out.println(other.n);
}

public void accessOtherPrivate(TestPrivate2 other) {
//      other.n = 10;//can not access,i konw
//      System.out.println(other.n);//
}
public static void main(String[] args) {
    new TestPrivate().accessOtherPrivate(new TestPrivate());
}

}

look at TestPrivate's method:accessOtherPrivate.why it can use other class's private field why?

4 Answers4

3

It does not access a field of another class. It access a private field of another object, of the same class.

In Java, you cannot access private fields of other classes because you are not supposed to know how they work internally. But you can still access private fields of other objects from the same class.

Arnaud Denoyelle
  • 29,980
  • 16
  • 92
  • 148
2

It's a common misconception that private fields are private to a particular instance. No. It's private to that particular class.

From Oracle Access Control Tutorial:

At the member level, you can also use the public modifier or no modifier (package-private) just as with top-level classes, and with the same meaning. For members, there are two additional access modifiers: private and protected. The private modifier specifies that the member can only be accessed in its own class.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
0

Because they are the same class. An object can reference private fields of its own class.

BTW, your TestPrivate2 class is just confusing the question and is not relevant.

Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
0
public void accessOtherPrivate(TestPrivate other)

you are accessing private field of TestPrivate in same class, its not another class, that is why its able to access n.

codingenious
  • 8,385
  • 12
  • 60
  • 90