Java anonymous operator or what is it called?

I would like to understand what it is called. I have seen this program on the oracle website. I saved the breakpoint and saw that this stat is called after the static block and before the constructor is called.

What is the significance of this statement?

{
    System.out.print("y ");
}

      

In this code:

public class Sequence {
    Sequence() {
        System.out.print("c ");
    }

    {
        System.out.print("y ");
    }

    public static void main(String[] args) {
        new Sequence().go();
    }

    void go() {
        System.out.print("g ");
    }

    static {
        System.out.print("x ");
    }
}

      

+3


source to share


3 answers


static {
        System.out.print("x ");
    }

      

Its a static block and its called whenever the class is loaded. In general, anonymous means that do not have any name as an anonymous class are clans that do not have any name and their implementation is provided right where it is required and cannot be reused



 {
        System.out.print("y ");
    }

      

As Eran noted, It an instance initialization block, and it executed whenever an instance is created

and is called before the constructor.

+1


source


This is an initializer block. It is executed whenever a new instance of the class is created. Most of the time, you really don't need this, because instance initialization can also be placed in the constructor. An initialization block is mainly for initializing anonymous inner classes for which you cannot define your own constructors (because you need the class name to define a constructor).



0


source


This is known as a static initialization block or static initializer.

See: https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

Personally, I prefer not to use them exactly for the reason stated in the documentation I posted.

There is an alternative to static blocks - you can write a personal Static method: the advantage of private static methods is that they can be reused later if you need to re-initialize a class variable.

0


source







All Articles