+ 5
What is the use of static block and constructor in java.
static block is used to execute a code(logic which u want to execute first with out using object) as soon as class is loaded. constructor is used to execute logic when object is created for that class.
2 ответов
+ 12
static block is similar for classes as constructors for objects. In a constructor you can initialize object properties, in a static block you can initialize class properties.
+ 6
Static block executed once while class-loading or initialize by JVM.
constructor executed every time while creating instance of that class.
Here is the example.
public class program
{
static{
System.out.println("Static block");
}
program(){
System.out.println("Constructor");
}
public static void main(String[] args) {
program p1 = new program();
program p2 = new program();
}
}
Output:
Static block
Constructor
Constructor