-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?

4
  • You can check this why-can-outer-java-classes-access-inner-class-private-members Commented Dec 5, 2018 at 11:14
  • Because Counter is defined inside Statics. If you defined Counter outside of Statics it would throw the error you're expecting. Commented Dec 5, 2018 at 11:15
  • We're dealing with static variables not instance variables. Those marking the question as duplicate are providing incorrect/irrelevant links/references. Commented Dec 5, 2018 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) Commented Dec 5, 2018 at 11:37

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

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)"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.