Generally, public variables can be accessed by everyone, and private variables can only be accessed from the current instance of the class. In your example, you are allowed access to the variable x
from the main
method, because this method is in the Static class.
If you're wondering why you are allowed to access it from a different instance of the Static class than the one you are currently using (which is usually not allowed for private variables), this is simply because static variables do not exist based on each instance, but based on each class. This means that the same static variable A can be accessed from all instances of A.
If this is not the case, no one will be able to access the private static variable at all, since it does not belong to one instance, but all of them.
source share