Accessing a static variable via an object reference in Java

Generally, public variables can be accessed by everybody, and private variables can only be accessed from within the current instance of the class. In your example you’re allowed to access the x variable from the main method, because that method is within the Static class.

If you’re wondering why you’re allowed to access it from another instance of Static class than the one you’re currently in (which generally isn’t allowed for private variables), it’s simply because static variables don’t exist on a per-instance basis, but on a per class basis. This means that the same static variable of A can be accessed from all instances of A.

If this wasn’t the case, nobody would be able to access the private static variable at all, since it doesn’t belong to one instance, but them all.

Leave a Comment