That static succeeded in only two braces?

What makes a static limit just two curly braces? Sorry for the initial question. I tried to find a tutorial on this, but could not find it. This use of static as: static {} is not clear to me. I found that it is used by others here at developerWorks . I thought it could be a multi-line or group modifier, and tried the code below, but other type modifiers give errors that are not like static ones.

public class MyClass { private volatile int v1=0; private final int v2=0; private static int v3=0; static { <----- No error here. int i1=0; String s1="abc"; double d1=0; }; final { <----- Error here. int i2=0; String s2="abc"; double d2=0; }; volatile { <----- Error here. int i3=0; String s3="abc"; double d3=0; }; } 
+5
source share
1 answer

This is a static initializer block that is used to initialize static members of a class. It is executed when the class is initialized.

Your example:

 static { int i1=0; String s1="abc"; double d1=0; }; 

does not make sense, because it declares variables that are only in scope until the execution of this block is completed.

A more significant static initialization block would be:

 static int i1; static String s1; static double d1; static { i1=0; s1="abc"; d1=0; }; 

This example still does not justify using a static initializer, since you can simply initialize this static variable when they are declared. The static initializer block makes sense when initializing static variables is more complicated.

+5
source

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


All Articles