Search code examples
javaaccess-modifiers

Private member of class accessed in main method


let's assume we have the following code:

 public class TestScope {
      private int a = 1;
         public static void main(String[] args) {
           TestScope ts = new TestScope();
           ts.a = 6;
           System.out.println(ts.a);
        }
    }

Why at line: ts.a = 6; I can get access to private variable a? I thought that private memebers cannot be accessed outside. I don't underestend this example.


Solution

  • It's because a and main(String[]) are both part of the definition of the class TestScope

    Private means that a variable or method can only be accessed inside the class definition. The fact that a is an instance variable doesn't mean it can't be accessed by a static public method in the same class.

    If the public static void main(String[]) was inside a different class, then it would not be able to access ts's a, because a is hidden from other classes.