Showing posts with label Static Variables. Show all posts
Showing posts with label Static Variables. Show all posts

Class members modifier: static

Members (fields and methods) of a class may be prefixed by the keyword static to distinguish them from instance (i.e.,non-static) members.
Static members belong to the class they are declared in but make no part of any instance of that class.
When the class is loaded, static variables (also called class variables) are initialized either explicitly by an initialization expression or given default values, these values are not part of the state of any object. In other words, static variables are not instantiated if an instance of the class is created.

There is no notion of object associated with static methods (also known as class methods), therefore a static method in a class can't access instance (i.e.,non-static) members. A static method can access directly other static members in the class. However static methods can always use a reference of the class' type to access its static and instance members.

Clients may access static members through the object reference of the class or simply by using the class name. Anyway, the class need not be instantiated to access its static members.

What's the lifetime of variables?

During the execution of a Java program, each variable has its own time within which it can be accessed. This is called the lifetime of the variable. We can determine the lifetime of variables by looking at the context in which they're defined. Anyway, we can distinguish between three contexts:

Instance variables:
Instance variables are class members. Every time you create an object from a class, a brand new copy of these instance variables is created for this object. Actually, creating an object from a class means, partially, creating copies of instance variables for that object. So each object has its own copy of instance variables which exist as long as the object they belong to exists. The values of these variables constitute what we call: the state of the object.

Static variables:
Static variables are also members of a class but can't belong to any object created from that class. So created objects from the class don't get their own copies of static variables. Therefore static variables are created only when the class is loaded at runtime. The existence of static variables is dependent only on the class itself. As a result, a static variable exists as long as its class exists.

Please note that an object of a class may still manipulate a static variable even though this object can't have its own copy of this static variable.

Local variables:
Also called automatic variables, are called local because their scope is the method or block within which they are declared. After the execution of the method or block completes, these local (non-final) variables are no longer accessible.