What does static block mean in Java?

Asked 2 years ago, Updated 2 years ago, 69 views

static {
    ...
}

I saw this code. I don't know what this is at all, and it doesn't make errors and compiles well. What does the 'static' block mean?

java static

2022-09-22 22:25

1 Answers

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


2022-09-22 22:25

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.