-1

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?

tomc
  • 76
  • 6
  • I think you're misunderstanding some base concepts. For example `it is also possible to call a private member of a different object`. This does not make any sense. As long as you have an instance of an object of type A within the same class you're still able to access it's member fields. – akortex Sep 17 '18 at 18:55
  • Keep in mind that your main method is in class A. `intVar` is accessible anywhere within the class A. – Roshana Pitigala Sep 17 '18 at 18:56

2 Answers2

3

Scope has nothing to do with objects, it has to do with classes. private means the associated keyword is only accessible within the same class, not the same object. "Accessible from within the same object" actually makes very little sense, since you write classes, not objects.

Consider, what would that rule ("accessible from within the same object") even look like in practice? What would it mean? You can't be "inside" an object while writing code, you can only be inside a class. If you consider this, you'll find that "within the same object" is an incoherent expression.

ubadub
  • 3,571
  • 21
  • 32
1

From the language spec:

A private class member or constructor is accessible only within the body of the top level class (§7.6) that encloses the declaration of the member or constructor. 

It's within the same top-level class, so it's accessible.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243