This post is especially targeted for that people who doesn't have any OOP concept ? :) oh no i am kidding. Ok, this post will discuss about the inheritance and its order of execution. Inheritance makes life easier and a very powerful channel to introduce the dynamic nature of polymorphism in your application. Sometimes people can get crazy if they don't know the actual order of execution of inheritance. Don't worry, i am sure this post will help you to remove your confusion in an easy way. Have a look at the following snippet. For better understanding of the reader it has been written in Java.
public class ClassE {
static int superInt = superIntMethod();
static int superIntMethod(){
System.out.println("1-Initializing static super int");
return 1;
}
static {
System.out.println("2-Executing super static block"); /* static initialization block */
}
static int superInstanceIntMethod() {
System.out.println("5-Initialzing superInstanceInt");
return 3;
}
private int superInstanceInt=superInstanceIntMethod();
ClassE(){
System.out.println("7-Running ClassE constructor");
}
{
System.out.println("6-Running super object initialization block");
}
public static void main(String[] args) {
new SubClass();
}
}
class SubClass extends ClassE {
static int subInt = subIntMethod();
static int subIntMethod(){
System.out.println("3-Initializing static sub int");
return 2;
}
static {
System.out.println("4-Executing sub static block"); /* static initialization block */
}
static int subInstanceIntMethod() {
System.out.println("9-Initialzing subInstanceInt");
return 3;
}
SubClass(){
System.out.println("10-Running SubClass constructor");
}
{
System.out.println("8-Running sub object initialization block"); /* object initialization block */
}
private int subInstanceInt = subInstanceIntMethod();
}
Just run it from your IDE and observe the output. Then match each line of output with this code. Enjoy :) .
No comments:
Post a Comment