At the time of class loading following sequence of steps is performed by JRE
(1). Static Data Members (if defined) are created in the Class Area.
(2). Static Initializer Block (if defined) is executed.
(3). Reference of the class which resulted in class loading is resolved i.e. operation represented by the reference is performed.
- class A
- {
- static
- {
- System.out.println(“A is loaded.”);
- }
- public A()
- {
- System.out.println(“A is instantiated.”);
- }
- }
- class B
- {
- static int b;
- static
- {
- b=5;
- System.out.println(“B is loaded.”);
- }
- }
- class C
- {
- static
- {
- System.out.println(“C is loaded.”);
- }
- public static void display( )
- {
- System.out.println(“Display( ) of C is invoked.”);
- }
- }
- class D
- {
- static
- {
- System.out.println(“D is loaded.”);
- }
- public static void main(String args[])
- {
- System.out.println(“Instantiating A………”);
- A x = new A();
- System.out.println(“Referencing static data member b of B……”);
- System.out.println(“b of B is : “ + B.b);
- System.out.println(“Invoking static method of C……”);
- C.display();
- System.out.println(“Instantiating A again.”);
- A y = new A();
- }
- }
class
E
{
static
int a = 5;
public static void main(String
args[])
{
System.out.println(“a = “ + a);
}
After compilation
|
class
E
{
static
int a;
static
{
a = 5;
}
----
----
}
-------------------------------------------------------------------------------------------------------
class
E
{
int
a = 5, b=6;
public static void main(String
args[])
{
E x = new E();
System.out.println(“a = “ + x.a);
System.out.println(“b = “ + x.b);
After compilation
|
class
E
{
int
a, b;
E( )
{
a = 5;
b = 6;
}
----
----
}
-------------------------------------------------------------------------------------------------------
class E
{
int a=5, b=6;
public E ()
{
System.out.println(“Default.”);
}
public E(int x)
{
a=x;
System.out.println(“One
parameterized.”);
}
public E(int x, int y)
{
b=y;
System.out.println(“Two
parameterized.”);
}
public void display()
{
System.out.println(“a = “ + a);
System.out.println(“b = “ + b);
}
public static void main(String
args[])
{
E x = new E();
E y = new E(10);
E z = new E(40, 50);
x.display();
y.display();
z.display();
}
}
After
compilation,
the compiler
will do the following for the same program
- class E{int a, b;public E(){a=5, b=6;System.out.println(“Default.”);}public E(int x){a=5, b=6;a=x;System.out.println(“One parameterized.”);}public E(int x, int y){a=5, b=6;b=y;System.out.println(“Two parameterized.”);}public void display(){System.out.println(“a = “ + a);System.out.println(“b = “ + b);}public static void main(String args[]){E x = new E();E y = new E(10);E z = new E(40, 50);x.display();y.display();z.display();}}
No comments:
Post a Comment