-1

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?

S34N
  • 7,469
  • 6
  • 34
  • 43
  • You can check this [why-can-outer-java-classes-access-inner-class-private-members](https://stackoverflow.com/questions/1801718/why-can-outer-java-classes-access-inner-class-private-members) – flyingfox Dec 05 '18 at 11:14
  • Because `Counter` is defined inside `Statics`. If you defined `Counter` outside of `Statics` it would throw the error you're expecting. – Mark Dec 05 '18 at 11:15
  • We're dealing with static variables not instance variables. Those marking the question as duplicate are providing incorrect/irrelevant links/references. – S34N Dec 05 '18 at 11:19
  • 1
    well, a static 'variable' is also a member of the class, so at least the second link is valid as duplicate (haven't checked the first, but probably same reasoning) – user85421 Dec 05 '18 at 11:37

2 Answers2

4

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

The Scientific Method
  • 2,374
  • 2
  • 14
  • 25
1

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

To your question:

"You are able to access the data (private static) variable from inside the class itself already" (Not outside the 'Statics' class)"

Vebbie
  • 1,669
  • 2
  • 12
  • 18