Вопрос

I dont really know what to call this thing so sorry for the vague title, so basically I have an understanding of static fields and methods in a class but no idea what the usage of the following is and does:

public class MyClass
{
     public MyClass() 
     {

     }

     static 
     {

     }
}

someone care to explain?

Это было полезно?

Решение

If you're referring to the static block:

static{

}

It gets executed before the main method; it is generally used to call other static methods and initialize static fields.

If you're referring to the constructor:

public MyClass(){

}

It used to construct an object when you create a new instance of it: MyClass instance = new MyClass();

Другие советы

static initialization blocks are used to initialize a class's static fields after the class is loaded.

In your case, you are doing nothing inside that block, so it is actually useless.

Its a static initialisation block. Which mean that the block is executed when the class is loaded, rather than when an instance is instantiated.

Useful for things like populating a map of values at class initialisation time.

Further information can be found in the java tutorial

Static blocks are called when the class is being loaded by the classloader (clinit bytecode section of the class)

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top