Answer the question
In order to leave comments, you need to log in
What are curly braces in Java?
I came across such a design in the classroom, I don’t even know how to search for it in Google.
static {
System.out.println("Инициализация Initable2");
}
class Initable2 {
static int staticNonFinal = 147;
static {
System.out.println("Инициализация Initable2");
}
}
Answer the question
In order to leave comments, you need to log in
This construct is called a static initialization block . There is also exactly the same dynamic initialization block , only without the static keyword.
Initialization blocks are needed to set initial values for class fields.
class Initable2 {
static int staticNonFinal;
public static void main(String[] args) {
System.out.println(staticNonFinal);
}
}
class Initable2 {
static int staticNonFinal;
// Вот этот блок будет добавлен к
// вашему классу во время компиляции.
static {
staticNonFinal = 0;
}
public static void main(String[] args) {
System.out.println(staticNonFinal);
}
}
class Initable2 {
static int staticNonFinal = 42;
static String a = "hello";
static Cache<String, Integer> b = CacheBuilder.newBuilder()
.maximumSize(100)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build();
}
class Initable2 {
static int staticNonFinal;
static String a;
static Cache<String, Integer> b;
static {
staticNonFinal = 42;
a = "hello";
b = CacheBuilder.newBuilder()
.maximumSize(100)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build();
}
}
class Initable2 {
static int staticNonFinal = 42;
static Map<Integer, String> statusCodes = new HashMap<>();
static {
statusCodes.put(200, "OK");
statusCodes.put(404, "Not Found");
statusCodes.put(418, "I'm a teapot");
}
}
class Initable2 {
static int staticNonFinal;
static Map<Integer, String> statusCodes;
static {
staticNonFinal = 42;
statusCodes = new HashMap<>()
statusCodes.put(200, "OK");
statusCodes.put(404, "Not Found");
statusCodes.put(418, "I'm a teapot");
}
}
well, it’s also written there - a static initialization block, you can display in the log that the class was initialized, you can fill in other static fields, in general, you can create various problems for yourself
public class InitDemo {
static String staticString;
String s;
static {
System.out.println("внутри static");
staticString = "Инициализация статического поля";
// s = "Тут нельзя обращаться к не static полям";
}
public InitDemo(String s) {
System.out.println("внутри конструктора");
this.s = s; // А в конструкторе уже можно
}
{
System.out.println("внутри {}");
s = staticString; // Это будет выполнено ДО конструктора
}
public static void main(String[] args) {
var initDemo = new InitDemo("Строка из конструктора");
System.out.println(initDemo.s);
}
}
внутри static
внутри {}
внутри конструктора
Строка из конструктора
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question