Wednesday 20 May 2015

Instance Control Flow In a Class

In my previous article I discussed about static control flow in a class and static control flow in parent and child relationship. let see what will happen at the time of creating class object .

At the time of creating an object the following sequence of events will be performed automatically by JVM.

1. Identification of instance members from top to bottom.
2. Execution of instance variable assignments and instance blocks from top to bottom.
3. Execution of constructor.


Output:

0
First instance block
Second instance block
InstaceFlow constructor
main() method......

I know the above program is bit confusing, I will try to elaborate more

At the time of creating an object the following sequence of events will be performed automatically[2].

At first all instance members of the class are identified (just identified , no assignment of variables and execution of instance blocks is done), observe [3] to [8] .

After identification variable assignment and execution of instace blocks starts from top to bottom so value 5 is assigned to int firstNumber[9] , the next instance block is executed here firstMethod() method is called ,  observe  firstMethod() is trying to print secondNumber which is not yet initialized so the default value “0” is printed,

now control flows back to instace block and the next statement  “First instance Block”[12] is displayed on console. After it the second instance block is executed and “Second instace Block” is printed[13], now the secondNumber is initialized[14]. Finally constructor is being executed [15]. (Generally object initialization done in constructors). then main () method next statement will be executed[16].

Note: Instance control flow is not one time activity for every object creation it will be executed but
static control flow is one time activity and it will be executed at the time of class loading.

I will be discussing more about constructors in my up coming post.

5 comments:

  1. Awesome explanation with diagram.

    ReplyDelete
  2. Existing without the answers to the difficulties you’ve sorted out through this guide is a critical case, as well as the kind which could have badly affected my entire career if I had not discovered your website.
    Surya Informatics

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Write more; that’s all I have to say. It seems as though you relied on the video to make your point. You know what you’re talking about, why waste your intelligence on just posting videos to your blog when you could be giving us something enlightening to readSurya Informatics

    ReplyDelete
  5. These are some great tools that i definitely use for SEO work. This is a great list to use in the future..
    代写cs 北美

    ReplyDelete