Static Keyword
Is used to define class members.
In a class we can have following 3 types of class members:-
- STATIC DATA MEMBERS
- STATIC INITIALIZE BLOCK
- STATIC METHODS.
(1) STATIC DATA MEMBERS
Represents class
attributes. A single copy of static data members is created when the class is
loaded. This copy can be shared by all the objects of the class.
For example -
- class A
- {
- int a, b;
- static int c;
- -------
- -------
- }
When we create objects of this class in some other class what
happens is explained in the given adjoining fig1.
Fig1.
For
the execution of a Java Application, memory is divided into three parts called
·
Stack
- LOCAL VARIABLES of methods are stored in STACK.
·
Heap
- OBJECTS are created in the HEAP.
·
Class
Area - STATIC DATA MEMBERS are saved
in CLASS AREA.
(3) STATIC METHODS.
- class A{int a, b;static int c;--------------------public static void main(String[] args){A x = new A();A y = new A();--------------------------}}
Memory Representation
During the execution of main() method of class A.
Static
Initializer Block- is used to initialize static
data members of a class.
Syntax
–
static
{
Statements
}
Static initialize is executed only once, just after a class is loaded.
In Java, a class can be loaded in either of the following ways:-
(1). Through Explicit Introduction.
(2). Through Implicit References.
In the first approach class to be loaded is explicitly introduced to the JRE.
Only a single class is loaded in an application using explicit introduction. Rests of the classes are loaded through implicit reference.
When a reference of a class is encountered first time in an already loaded class then JRE implicitly loads it before performing the operation represented by the class reference.
- class A
- {
- public static void main(String[ ] args)
- {
- B x = new B();//Reference of B is contained in A
- -------------
- -------------
- }
- }
- class B
- {
- -------------
- -------------
- }
No comments:
Post a Comment