Search code examples
javaoopaccess-modifiersstatic-variablesprivate-members

Assessing a static private variable (Java), Shouldn't it be illegal?


Before you mark this questions as duplicate, please make sure you provide your own explanation. Thank you. Please take note of the private STATIC variables, they are NOT instance variables.

I have the following scenario:

public class Statics {
   private static class Counter {
        private int data = 5; //Declared as private.

//        public Counter() throws IllegalAccessException {
//            throw new IllegalAccessException();
//        }

        public void bump(int inc) {
            inc++;
            data = data + inc;
        }
    }

    public static void main(String[] args) throws IllegalAccessException {
        Counter c = new Counter();
        int rnd = 2;
        c.bump(rnd);

        c.data = 0; //How this possible? It is declared as private.

        System.out.println(c.data + " & "+ rnd);
    }
}

Outputs: 0 & 2

My question is, how is it even possible that I am able to access the data (private static) variable from outside the class.

In Java, we know that members of the private access modifier cannot be accessed from outside the class.

We always use setters & Getters to modify values of private variables, shouldn't we? Am I missing something?


Solution

  • Because class Counter is private member of class Statics, Private members of a class are accessible from within their class.