Thursday, December 13, 2018

Java OOPS: Instance Control Flow

Hi All,

After explaining the static control flow , in this post I will explain how instance control flow , takes place in any java class.

Before we start , if you need to understand about the instance block , please take a look on this wonderful tutorial : Instance Initializer Block

Same as the static control flow , it also has some rules for executing. But in static control flow , it will automatically load by JVM , before the execution of Main Method because of static property. But in instance control flow , block/variables/methods will not execute until unless the object creation will not take place.Let's take a look with an example:

Example:

public class InstanceControlFlow {

int i =10;

{
m1();
System.out.println("First Instance Block!");
}

InstanceControlFlow(){
System.out.println("Constructor");
}

public static void main(String[] args){
System.out.println("Main Method");
}

public void m1(){
System.out.println(j);
}

{
System.out.println("Second Instance Block!");
}

int j =20;
}



Output :
Main Method


Explanation:
Unlike the static control flow , here we can see that because we are not creating any object so only main method with identify and main method execution will happen.So output is "Main Method"
only.

Now we will try same code , after creating the object in main method , to check again for result.

Whenever we are execute any java class , first Static Control Flow will be executed 
In the static control flow , if we are creating an object  , the following sequence of events will be executed , as the part of Instance Control Flow

  • Rule 1: Identification of instance members from top to bottom 
  • Rule 2: Execution of instance variable assignments and instance blocks from top to bottom 
  • Rule 3: Execution of constructor 
So the base control flow will be like:
First Static Control Flow 
After that Instance Control Flow 

So Final Sequence will be :

  1. Identification of static members from Top to Bottom  (static control flow)
  2. Execution of static variable assignment and static blocks from top to bottom  
  3. (static control flow)
  4. Execution of main method  (static control flow)
  5. Identification of instance members from top to bottom   (instance control flow)
  6. Execution of instance variable assignments and instance blocks from top to bottom  (instance control flow)
  7. Execution of constructor    (instance control flow)
It means whenever any java class is going to be execute , first the static control flow will perform , then if object creation has been done , then instance control flow sequence would take place.

So first I am showing  the same above example but with object creation, after that I will explain the detail with sequences of execution with output.

public class InstanceControlFlow {

int i =10;

{
m1();
System.out.println("First Instance Block!");
}

InstanceControlFlow(){
System.out.println("Constructor");
}

public static void main(String[] args){
InstanceControlFlow instanceControlFlow = new InstanceControlFlow();

System.out.println("Main Method");
}

public void m1(){
System.out.println(j);
}

{
System.out.println("Second Instance Block!");
}

int j =20;
}

Here in above InstanceControlFlow instanceControlFlow = new InstanceControlFlow(); , due to this line , all instance member of this class will come in picture.

Now when we will execute this program , first static control flow will execute , then after the instance control flow i.e.,

-> First it will identify for static members from top to bottom [IN OUR EXAMPLE WE DON'T HAVE ANY]

-> Second compiler will execute of static variable assignment and static blocks from top to bottom
[IN OUR EXAMPLE WE DON'T HAVE ANY]

-> Third it will execute main method [IN OUR CASE FROM HERE EXECUTION WILL START ]

-> In Main Method the object has been created , so it will start our instance control flow . 

Let's take a brief look :





Now if we compile the code , we will get same output , as mentioned in above picture.

If again object has been created , then again output 1-4 will be repeated , let's take a look ,I have just changed the main method code in above example:

public static void main(String[] args){

InstanceControlFlow instanceControlFlow = new InstanceControlFlow();

System.out.println("Main Method");

InstanceControlFlow instanceControlFlow1 = new InstanceControlFlow();

}

Output :
0
First Instance Block!
Second Instance Block!
Constructor
Main Method
0
First Instance Block!
Second Instance Block!
Constructor

Hence we can see that , the number of object creation has been done in main method , the process will be repeated with same times.

Note: Static control flow is one time activity which we will be performed at the time of class loading. 
But instance control flow is not one time activity and it will be performed for every object creation.

Object creation is the most costly operation, if there is no specific requirement then it is not recommended to create object.

That's it. I would suggest first compile this code by yourself for more clarity. 



Wednesday, December 12, 2018

Java OOPS: Static Control Flow


Hi ,

This post is related to the static control flow. Before starting we should have the clear understanding of what is static block, how it is written in our java code. So for that please check this wonderful tutorial : static keyword in java

Now the point is what is static control flow. When everything is static in our class from top to bottom , what will be the execution flow , of that class. This will be known as Static Control Flow.

First I will show one example of this type scenario , then I will explain about the rules , which we have to follow to execute and then will implement those rules in my example to get the final output.

Example:

public class StaticControlFlowDemo {

static int i = 10;

static{
     m1();
     System.out.println("First static block!");
}

public static void main(String[] args){
     m1();
     System.out.println("Main Method");
}

public static void m1(){
     System.out.println(j);
}

static{
     System.out.println("Second static block!");
}

static int j =20;

}

The above is a simple java class, where all the members of the class are static. Now in this class , we will check what will be output and why? Which stepsl should be followed behind that output?

Whenever we are executing a java class , the following sequence of steps/rules  will executed , as the part of Static Control Flow: 


  • Rule 1 : Identification of static members from Top to Bottom  
  • Rule 2 : Execution of static variable assignment and static blocks from top to bottom 
  • Rule 3: Execution of main method 


=> Firstly we need to identify the static members from top to bottom 

=>In Second step we have to execute all the static variables and static blocks /members from top to bottom

=>In Third step we will execute the main method.

In this way we will execute above java class. I would suggest to write this code in a hard paper and apply the steps one by one , for better clarity. I have tried the same rules, please take a look on below image :



I have mentioned all the steps and with different colors : 

RULE 1 

RULE 2

RULE 3 
Here I have used two states for variables [RIWO] and [R&W] states, full form of these states are :

RIWO -> Read Indirectly & Write Only  (Initial State)
R&W -> Read and Write  

These state I will explain later.

With above formatting I have added the steps in above image. Please take a look . After applying the steps  we will get the following output:

Output :


0
First static block!
Second static block!
20
Main Method

And if we compile the code , it will show same output which I have mentioned.


Inside a static block if we are trying to read a variable that read operation is called Direct Read.
If we are calling a method , and within that method if are trying to read a variable , that read operation is called InDirect Read.

public class Test {
static int i = 10;
static{
m1();
System.out.println(i);     //Direct Read
}
public static void m1(){
System.out.println(i);     //Indirect Read
}
}



If a variable is just identified by the JVM , and the original value not yet assigned . Then the variable is said to be in READ INDIRECTLY & WRITE ONLY STATE . [RIWO]

If a variable is in RIWO state , then we can't perform Direct Read, but we can perform Indirect Read. 

Example 1:


public class StaticControlFlowDemo {
static int i = 10;
static{
System.out.println(i);  
//Direct Read
}
public static void main(String[] args){
System.out.println("Main Method");
}
}
Output :
10
Main Method


Example 2:

public class StaticControlFlowDemo {
static{
System.out.println(i);
}
public static void main(String[] args){
System.out.println("Main Method");
}
static int i = 10;
}

Output :

error: illegal forward reference




Example 3:

public class StaticControlFlowDemo {
static {
m1();     
//Indirect Read
}
public static void m1(){
System.out.println(i);
}
public static void main(String[] args){
System.out.println("Main Method");
}
static int i = 10;
}
Output :

0
Main Method

So in this way , static control flow works in java. I would suggest , to compile this code by yourself and apply the rules which is explained and check the output for better understanding. 

Java OOPS: Inheritance (Overriding) Part 7 With Super keyword

Hi ,

In previous post , we checked that how method hiding takes place. Now in this post I am going to share some usage of super keyword.
In common language we can say that super keyword is used to invoke , parent class variable , method or constructor by child class members.

Let's take a look on some examples for better understanding:

Example :1  

Usage of super keyword , for variable invocation of Parent class. 

public class InheritanceDemo1 {
public static void main(String [] args){
Child child = new Child();
child.m1();
}
}
class Parent {
String color = "red";
public void m1(){
System.out.println("This is parent class m1 method");
}
}
class Child extends Parent {
String color = "green";
public void m1(){
System.out.println("Color Value in Child Class:"+color);
System.out.println("Color Value in Parent Class:"+super.color);
}
}

Output :

Color Value in Child Class:green
Color Value in Parent Class:red

Explanation:  

In this example we can see that I have used super.color to get the color value from Parent class.


Example :2  

Usage of super keyword , for method invocation of Parent class. 

public class InheritanceDemo1 {
public static void main(String [] args){
Child child = new Child();
child.m1();
}
}
class Parent {
public void m1(){
System.out.println("This is parent class m1 method");
}
}
class Child extends Parent {
public void m1(){
System.out.println("This is child class m1 method");
super.m1();
}
}

Output :

This is child class m1 method
This is parent class m1 method

Explanation:  

In this example we can see that I have used super.m1(); to call the m1() of Parent class.


Example :3

Usage of super keyword , for calling the parent class constructor 

public class InheritanceDemo1 {
public static void main(String [] args){
new Child();
}
}
class Parent {
public Parent() {
System.out.println("I am in parent class constructor");
}
}
class Child extends Parent {
public Child() {
super();
System.out.println("I am in child class constructor");
}
}

Output :

I am in parent class constructor
I am in child class constructor

Explanation:  

In this example we can see that I have used super(); to call the constructor of Parent class.



Java OOPS: Inheritance (Overriding) Part 6 With Static Methods

Hi All ,

In previous post we checked how various methods works in overriding. Now in this post we will take a look how static method works in overriding concept.

Case I :  

Let's take a look:

public class InheritanceDemo1 {
public static void main(String [] args){
Child child = new Child();
child.m1();
}
}
class Parent {
public static void m1(){
System.out.println("This is parent class m1 method");
}
}
class Child extends Parent {
public void m1(){
System.out.println("This is child class m1 method");
}
}

Output :

error: m1() in Child cannot override m1() in Parent
overridden method is static


Explanation:  

In this example we can see that we can't override a static method as non-static , otherwise we will get compile time error. 



Case II :  


Same  previous case , we are going to check , with overriding the non-static method from Parent to static Child class method .Let's take a look:

public class InheritanceDemo1 {
public static void main(String [] args){
Child child = new Child();
child.m1();
}
}
class Parent {
public void m1(){
System.out.println("This is parent class m1 method");
}
}
class Child extends Parent {
public static void m1(){
System.out.println("This is child class m1 method");
}
}


Output :



error: m1() in Child cannot override m1() in Parent

overriding method is static

Explanation:  

In this example we can see that we can't override a non-static method as static , otherwise we will get compile time error. 




Case III :  


Now in this case we will check if both parent and child class methods are static then , we won't get any compile time error . It seems overriding concept applicable for static methods ,but it is not overriding and it is Method Hiding .Let's take a look:

public class InheritanceDemo1 {
public static void main(String [] args){

Parent parent1 = new Child();
parent1.m1();

Parent parent2 = new SubChild();
parent2.m1();
}
}
class Parent {
public static void m1(){
System.out.println("This is parent class m1 method");
}
}
class Child extends Parent {
public static void m1(){
System.out.println("This is child class m1 method");
}
}
class SubChild extends Parent {
public static void m1(){
System.out.println("This is sub child class m1 method");
}
}

Output :

This is parent class m1 method
This is parent class m1 method

Explanation:  

In this example we can see that it is method hiding , method resolution is always takes care by compiler based on reference type. 

Hidden methods are in Static context, I believe. Static methods are not overridden, because the resolution of method calls done by the compiler at the compile time itself. So, if you define a static method in the base class with the same signature as that one present in the parent class, then the method in the subclass hides the method inherited from super class.

If both Parent and Child class methods are non-static , then it will become overriding .In that case output will be :

Output :

This is child class m1 method
This is sub child class m1 method

Tuesday, December 11, 2018

Java OOPS: Inheritance (Overriding) Part 5 Various Rules

Hi All,

We have seen various cases/ rules of overriding in my previous posts . Now in this post I am listing some more rule on the basis of different type of methods for ex: final, synchronized , native etc. I am showing the rough syntax to show just rules. You can check by implementing these rules in your code . ;)

Case I :  

Parent{
      final m1(){} 

}
Child extends Parent {
      final/non-final m1(){}
}


Valid Or Not :
Not Valid



Case II :  

Parent{
       non-final m1(){}
}
Child extends Parent {
       final m1(){}
}

Valid Or Not :
Valid

Case III :  

Parent{
     abstract m1(){}
}
Child extends Parent {
     non-abstract m1(){}
}

Valid Or Not :

Valid



Case IV :

 Parent{
       non-abstract m1(){}
 }
Child extends Parent {
       non-abstract m1(){}
}


Valid Or Not :
Valid



Case V :


 Parent{     
      synchronized m1(){}
}
Child extends Parent {
      non-
synchronized m1(){}
}



Valid Or Not :
Valid

Case VI :


Parent{      
     non-synchronized m1(){}
 }
Child extends Parent {
     
synchronized m1(){}
}


Valid Or Not :
Valid



Case VII :


Parent{  
      native m1(){}
}
Child extends Parent {
      
non-native m1(){}
}





Valid Or Not :
Valid

Case VIII :

Parent{      
      non-native m1(){}
}
Child extends Parent {
       
native m1(){}
}

Valid Or Not :
Valid

Case IX :

Parent{      
       void m1(){}
}
Child extends Parent {
       public
 void m1(){}
}


Valid Or Not :
Valid

Case X :

Parent{      
      public  void m1(){}
}
Child extends Parent {
     
void m1(){}
}

Output :
error: m1() in Child cannot override m1() in Parent
attempting to assign weaker access privileges; was public

Note : While overriding we can't reduce scope of access modifier , but we can increase the scope.  private < default < protected < public   
Benefit of this rule is , because of overriding outside members should not be affected . So because of this reason we can increase the scope but not decrease.

Parent        public             protected                  default                                    private
                      |                          |                              |                                              |
Child          public            protected/public        default/protected/public     overriding is not applicable