What does this โ€œstaticโ€ mean and why is it

public class tt {
static{
    System.out.println("class tt");
    }
}

This is the first time he encounters him, and they wonder what it is and what he used to

+3
source share
5 answers

This is a static class initializer. When the class is loaded, the static initializer starts. This is similar to a constructor, but for a class, not for individual objects.

Several static initializers can be displayed in the class, as well as direct initializers for static variables. They will be combined into one initializer in the order in which they are declared. For example, the following will print โ€œfooโ€ to stdout whenever the class loads (usually once for the application).

public class Foo {

  static String a;

  static {
    a = "foo";
  }

  static String b = a;

  static {
    System.println(b);
  }

}
+5

- , {}, . :

static {
    // whatever code is needed for initialization goes here
}

, . , . - :

class Whatever {
    public static varType myVar = initializeClassVariable();

    private static varType initializeClassVariable() {

        //initialization code goes here
    }
}

, , .

+4

http://download.oracle.com/javase/tutorial/java/javaOO/initial.html

, .

public class A {

    static {
        System.out.println("A from static initializer"); // first 
    }

    public A(){
        System.out.println("A"); // second
    }

    public static void main(String[] args){
        new A();
    }
}
+2

. , JVM , - (, , , ,...).

+1

. , :

private static int staticField = someMethod();

, , try/catch.

0

Source: https://habr.com/ru/post/1780188/


All Articles