-1

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?

SimpleJack
  • 151
  • 1
  • 12

4 Answers4

2

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();

Josh M
  • 11,611
  • 7
  • 39
  • 49
1

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.

LexLythius
  • 1,904
  • 1
  • 12
  • 20
1

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

0

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

David Lakatos
  • 319
  • 3
  • 7