MY mENU


Tuesday 15 January 2013

What JVM does internally when an object is created?


When we create object first control is sent to invoked constructor, but its logic will not be executed, instead non-static variables and non-static blocks are executed first in the order they are defined from top to bottom, then after constructor logic is executed.
If all non-static variable and non-static blocks execution is completed, we can say object creation is completed. If constructor execution is completed, we can say object initialization is completed. New key word will initialize the non static variables with default and assigned values. Constructors will reinitialize objects only with developer or given values.

Who will initialize default and assigned values to non-static variables?

new keyword. Constructor reinitialize object only with developer or user given values.

Responsibilities of new keyword and constructor in creating object:
the responsibilities of new keyword is
- in identification phase it creates non-static variables with default values in heap area in continuous memory locations and also identifies non-static blocks.
- in execution phase it executes variables and non-static blocks in the order they defined, means it initialized non-static variables with assigned values and executes non-static block logic in JSA by creating separate stack frame.
- then after execution of non-static variable and non-static blocks, new keyword gives control back to constructor to perform initializes operations.

the responsibilities of Constructor is reinitializing non-static variables means object with developer or user given values as per its logic.
- then finally new keyword returns object reference to calling area, then it is stored in destination referenced variable.

Constructors in JAVA

Constructor: it is a special method given in OOP language for creating and initializing object. In java, constructor role is only initializing object, and new keyword role is creating object. In C++, constructor alone creates and initializes object. If we do not define constructor compiler will define constructor.
Rules in defining constructor:
 Constructor name should be same as class name. Every class object is created by using the same new keyword, so it must have information about the class to which it must create object. For this reason constructor name should be same as class name.
  1. it should not contain return type. If place return type in constructor will leads to compile Error because compiler and JVM consider it as method.
  2. IT should not contain modifiers
  3. In its logic return statement with value is not allowed.
  4. It can have all four accessibility modifiers.
  5. It can have parameters.
  6. It can have throws clause – it means we can throw exception from constructor.
  7. It can have logic, as part of logic it can have all java legal statement except return statement with value
  8. We can place return; in constructor.

Class Example {
Example {
Statements except return;
} }

Calling Constructor:  it must be called along with “new” keyword; else it leads to compile time error.

Can we define a method with same class name?
Yes, it is allowed to define a method with same class name. No compile time error and no runtime error are raised, but it not recommended as per coding standards.

How compiler and JVM can differentiate constructor and method definitions; and invocations if both have same class name?
By using return type, if there is return type it is considered as method else it considered as constructor.
By using new keyword, if new keyword is used in calling then constructor is executed else method executed.
We can define empty class, but after compilation it will have constructor definition that is placed by compiler. So really it is not an empty class.

How can we know that compiler places constructor in class file?
We should use “javap” tool. It is a java binary file available in “jdk\bin” folder. It is used to decompile class file to check that class members. Javap tool only displays class member’s prototype. It does not show body and logic.  Ex: javap classname
Java supports 3 types of constructors:

Default constructor: the compiler given constructor is called default constructor. It does not parameters and logic except super() method call.

No argument/non-parameterized constructor: the developer given constructor without parameter is called no-arg /non-parameterized constructor.

Parameterized constructor: the developer given constructor with parameter is called parameterized constructor. In this we can have logic.

Super() method call must also be placed as a first statement in developer given constructors. If developer does not place it, compiler will place this statement.

why compiler given constructor is called default constructor?
Because it obtain all its default properties from its class they are:
Its accessibility modifier is same as its class accessibility modifier
Its name is same as its class name.
It does not have parameters and logic.

Why compiler defines default constructor without logic and parameters?
Because compiler does not know logic required for your class. The objects initialization logic is different from one class to another class.
But it places super() method call in all constructors because it is generic logic required for every class for calling super class constructor in order to initialize super class non-static variables when subclass object is created.
Since there is no logic in default constructor, compiler defines constructor without parameters.

When developer must provide constructor explicitly?
If we want to execute some logic at the time of object creation that logic may be object initialization logic or some other useful logic.

We must create object of a class by using new keyword and available constructor.
To initialize object dynamically with the user given values then we should defined parameterized constructor.

In a class we can define multiple constructors, but every constructor must have different parameters type or parameters order. So in a class we can define one no-argument constructor + ‘n’ number of parameterized constructors.

Defining multiple constructors with different parameter types/order/list is called 
constructor overloading.
Ex:  Example () {}
        Example (int i) {}
        Example (String str) {}

NON-Static BLOCK: (NSB) a class level block which doesn’t have prototype is called non-static block.
We should define non-static block to execute some logic only at the time of object creation irrespective of the constructor used in object creation. NSB is executed automatically by JVM for every object creation in java stacks area by creating separate stack frame. NSB always executed before constructor.
Class example {
{
Sopln (“NSB Block”);  }
Example () {  Sopln (“Constructor”); }
}
We can define multiple non static blocks. When an object is created first all non static variables and non-static blocks are executed in the order they are defined from top to bottom, then the invoked constructor logic is executed.

Compile Time Error: illegal forward reference: a class level variable should be accessed directly before its creation statement either from other variables, from blocks. It leads to that error. But it is possible to access those variables from methods and constructors, because they are always executed after variable execution. Call static variable with “class name”, and non static variable with “this”.

Recursive method and constructor call: calling a method or constructor from its own block is called recursive method or constructor call. In both cases program is terminated with java.lang.StackOverFlowError.
Because due to this call stack frames are created continuosly without destroying previous stack frames. Due to this reason at some point of time there will not be memory in thread to create new stack frame.

Class Example{
Static void m1(){
Sopln(“m1”);
M1();
} }

We can create object at class level using static and non-static referenced variables, but the object creation using non-static referenced variable also leads to java.lang.StackOverflowError. it is possible to create object at class level using static referenced variable. Object of same class should not be created using non static referenced variable or in non-static block or in same constructor it leads to exception above.
Class A {
Static  A a=new A();
A a=new A(); /// it leads to execption.
A(){
}
}