Saturday, 2 June 2018

static block instance Block in java------------





Instance initialization block in java can be used to initialize instance variables in java.
Static initialization block in java can be used to initialize static variables in java.
==================================================================================

//Static block
Static blocks are also called Static initialization blocks in java.
Static block executes when class is loaded in java.
static blocks executes before instance blocks in java.
Only static variables can be accessed inside static block in java
static blocks can be used for initializing static variables or calling any static method in java.
this keyword cannot be used in static block in java.

======================================================================================
Instance blocks:-
Instance blocks are also called instance initialization blocks in java
Instance block executes when instance of class is created in java.
Also known as non-static initialization block in java.
instance blocks executes after static blocks in java.
Static and non-static variables (instance variables) can be accessed inside instance block in java.
instance blocks can be used for initializing instance variables or calling any instance method in java.
this keyword can be used in instance block in java.



========================================================================================

package javaresearch;

public class TestData {

static
{
System.out.println("Static Block");


}

public TestData()
{
System.out.println("Constructor");
}


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

public static void main(String[] args) {
TestData td=new TestData();

}

}

============================================================================================

o/p-------------------------
Static Block
Instance Block
Constructor

============================================================================================

package javaresearch;

public class SuperClassDemo {

static
{
System.out.println("Super class static block");
}


{
System.out.println("Super class Instance block");
}

SuperClassDemo()
{
System.out.println("Super class Constructor");
}

}


================================================================================================


package javaresearch;

public class SubClassDemo extends SuperClassDemo
{

static
{
System.out.println("Sub class static block");
}


{
System.out.println("Sub class Instance block");
}

SubClassDemo()
{
System.out.println("Sub class Constructor");
}

public static void main(String[] args) {
SubClassDemo scd=new SubClassDemo();

}

}


============================================================================================

o/p:-------------------------
Super class static block
Sub class static block
Super class Instance block
Super class Constructor
Sub class Instance block
Sub class Constructor

No comments:

Post a Comment