Wednesday, 7 September 2016

Static flow of inheritance

static context in inheritance :-
In java applications, static context is represented in the form of the following elements.
1.       static variable
2.       static method
3.       static block
where static variable and static block are recognized and executed at the loading the respective class byte code to the memory, where static method will be recognized and executed t the time of calling that method.
In case of inheritance, when we are creating object for sub class, JVM has load sub class byte code to the memory, but before loading sub class byte code, first, JVM has to load Super class byte code to the memory then sub class byte code to the memory.
In case of inheritance, JVM will load all the classes byte code to the memory right from super class to sub class ordering. In this case, if we provide static context in the classes then JVM will recognize and execute that static context at the time of coding the classes byte code to the memory.

Ex code1:-
class A
{
                static
                {
                                System.out.println("SB-A");
                }
}
class B extends A
{
                static
                {
                                System.out.println("SB-B");
                }  
}
class C extends B
{
                static
                {
                                System.out.println("SB-C");
                }
}
class Test
{
                public static void main(String[] args)
                {
                                C c=new C();
                }
}
Output:-
SB-A
SB-B
SB-C
Ex code 2:-
class A
{
                static int m1()
                {
                                System.out.println("m1-A");
                                return 10;
                }
                static
                {
                                System.out.println("SB-A");
                }
                static int i=m1();
}
class B extends A
{
                static int j=m2();
                static
                {
                                System.out.println("SB-B");
                }
                static int m2()
                {
                                System.out.println("m2-B");
                                return 30;
                }
}
class C extends B
{
                static
                {
                                System.out.println("SB-C");
                }
                static int k=m3();
                static int m3()
                {
                                System.out.println("m3-C");
                                return 40;
                }
}
class Test
{
                public static void main(String[] args)
                {
                                C c1=new C();
                                C c2=new C();
                }
}
Output:-
SB-A
m1-A
m2-B
SB-B
SB-C

m3-C

No comments:

Post a Comment