I am quite knowledgeable about scopes, but following rule surprised me.
How is it possible that System.out.println(intVar)
doesn't throw compile error, though intVar
is private?
Consider the following code:
class A {
private int intVar = 1;
public static void main(String[] args) {
A a = new A(); //INITIALISATION OF NEW OBJECT
System.out.println(a.intVar); //ACCESSING PRIVATE MEMBER OF DIFFERENT OBJECT - COMPILES
}
}
I understand that making a member private means you are making it accessible only from within the same class.
BUT it is also possible to call a private member of a different object if I am within the same class.
Note, I understand why a private member of an inner class is accessible in an outer class. But what is the logic in making private class member inaccessible to anything outside the class but not outside its object if class should be a blueprint of object? Isn't it kinda breaking encapsulation?