Question

In the following simple piece of code, surely this should produce an error, but instead it logs 's' and then '10'. Are private fields not only visible from within their class, even if that class is static?

public class Test  {
    public static void main(String[] args) {
        TestClass myObj = new TestClass();

        myObj.test();

        System.out.println(myObj.myField);
    }


    static class TestClass {
        private int myField = 5;

        private void test() {
            System.out.println("s");
        }
    }
}
Was it helpful?

Solution

The fields are all within the Test class, so all the classes and fields within Test can see each other even when private. Essentially the private keyword says "Only stuff in Test can see me" and in this case everything is in Test.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top