-1

In the below code:

 class Person {
    private String name;
    private int x = 5;
    public Person(String name) {
        this.name = name;
    }
    public void invoke(Person p) {
        System.out.println(p.name);
    }
}
class YU {
    public static void main(String args[]) {
        Person p1 = new Person("P1");
        Person p2 = new Person("P2");
        p1.invoke(p2);
    }
}

When I invoke the method "invoke" on instance p1 and pass p2 as argument, I am able to access p2's private instance variable directly inside the invoke method which was invoked on the instance p1. Why is this not throwing a compile time error? Even though p2 is an instance of Person class, but the method is invoked on p1 and not p2 and hence, only p1's private variables should be directly accessible. Please clarify.

singhakash
  • 7,891
  • 6
  • 31
  • 65
paidedly
  • 1,413
  • 1
  • 13
  • 22

1 Answers1

2

When I invoke the method "invoke" on instance p1 and pass p2 as argument, I am able to access p2's private instance variable directly inside the invoke method which was invoked on the instance p1. Why is this not throwing a compile time error?

Because it isn't an error. name is private to the Person class, not to a specific instance of the class. There is no per-instance privacy. Java's access control relates to what class (and by extension, package) the code is part of, not what instance it's been called on.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875