That's called an initialization block.
class InitBlock{
static {
/* Class initialization block */
}
{ /* instance initialization block */}
}
It's usually like this.
Since the initialization of the instance variable mainly uses a constructor, the instance initialization block is rarely used. Instead, if there is a code that should be common to all constructors in the class, it is good to put it in the instance initialization block without putting it in the constructor to reduce duplication of the code.
Car(){
System.out.println ("Create Car Instance");
color="White";
gearType="Auto";
}
Car(String color, String gearType){
System.out.println ("Create Car Instance");
this.color = color;
this.gearType=gearType;
}
--------------------------------------------
// Block Instance
{ System.out.println ("Create Car Instance"); }
Car(){
color="White";
gearType="Auto";
}
Car(String Color, String gearType){
this.color=color;
this.gearType=gearType;
}
This eliminates the duplication of code.
class BlockTest{
static { // class initialization block
System.out.println("static { }");
}
{ // Block instance initialization
System.out.println("{ }");
}
public BlockTest(){
System.out.println ("creator");
}
public static void main(String args[]){
System.out.println("BlockTest bt = new BlockTest(); ");
BlockTest bt = new BlockTest();
System.out.println("BlockTset bt2 = new BlockTest();");
BlockTest b2 = new BlockTest();
}
}
Execution result: static { } BlockTest bt = new BlockTest(); { } constructor BlockTset bt2 = new BlockTest(); { } constructor
© 2024 OneMinuteCode. All rights reserved.