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.
It’s because
aandmain(String[])are both part of the definition of the classTestScopePrivate 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 accessts‘sa, becauseais hidden from other classes.