Why am I able to access a private instance variable of one instance from a method invoked on another instance of the same object? [duplicate]

This question already has an answer here:

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.


Source: oop

Leave a Reply