Search code examples
javavariablesprivate

Why can I access the private variable in this case?


I have private int a variable and I access to this variable via test.a. Why this is ok? I thought that this way is possible only if I had public int a variable, not private.

public class Test {

    private int a;

    public static void main(String[] args) {
        Test test = new Test(5);
        System.out.println(test.a);
    }

    public Test (int a) {
        this.a = a;
    }
}

Solution

  • You can access it because your main method is in the same class.