Блоки инициализации представляют собой код, заключенный в фигурные скобки и размещаемый внутри класса вне объявления методов или конструкторов.
Существуют статические и нестатические блоки инициализации.
Статический блок инициализации выполняется в момент загрузки класса в JVM загрузчиком классов (Class Loader).
public class StaticInitialization {
static {
System.out.println("Статическая инициализация");
}
}
Нестатический блок инициализации выполняется в момент создания класса (
new).
public class NonstaticInitialization {
{
System.out.println("Нестатическая инициализация");
}
}
Несколько блоков инициализации выполняются в порядке следования в коде класса.
Блок инициализации способен генерировать исключения, если их объявления перечислены в throws всех конструкторов класса.
Блок инициализации возможно создать и в анонимном классе.
#java #initialization #block #static
Please open Telegram to view this post
VIEW IN TELEGRAM
👍9❤3🔥1
Сначала вызываются все статические блоки в очередности от первого статического блока корневого предка и выше по цепочке иерархии до статических блоков самого класса.
Затем вызываются нестатические блоки инициализации корневого предка, конструктор корневого предка и так далее вплоть до нестатических блоков и конструктора самого класса.
1️⃣ Parent static block(s) → Child static block(s)
2️⃣ Parent non-static block(s) → Parent constructor
→ Child non-static block(s) → Child constructor
Пример:
public class Alert {
public Alert(String message) {
System.out.println(message);
}
}
public class Parent {
public static Alert statVar1 = new Alert("Parent: static variable (statVar1)");
public static Alert statVar2;
static {
statVar2 = new Alert("Parent: static initialization block (statVar2)");
}
public Alert var1 = new Alert("Parent: variable (var1)");
public Alert var2;
{
var2 = new Alert("Parent: initialization block (var2)");
}
public Alert var3 = new Alert("Parent: variable (var3)");
public static Alert statVar3 = new Alert("Parent: static variable (statVar3)");
public Alert contructorVar;
public Parent() {
contructorVar = new Alert("Parent: constructor (contructorVar)");
}
}
public class Child extends Parent {
public static Alert statVar1 = new Alert("Child: static variable (statVar1)");
public static Alert statVar2;
static {
statVar2 = new Alert("Child: static initialization block (statVar2)");
}
public Alert var1 = new Alert("Child: variable (var1)");
public Alert var2;
{
var2 = new Alert("Child: initialization block (var2)");
}
public Alert var3 = new Alert("Child: variable (var3)");
public static Alert statVar3 = new Alert("Child: static variable (statVar3)");
public Alert contructorVar;
public Child() {
contructorVar = new Alert("Child: constructor (contructorVar)");
}
}
public class Test {
public static void main(String[] args) {
new Child();
}
}
Вывод консоли:
Parent: static variable (statVar1)
Parent: static initialization block (statVar2)
Parent: static variable (statVar3)
Child: static variable (statVar1)
Child: static initialization block (statVar2)
Child: static variable (statVar3)
Parent: variable (var1)
Parent: initialization block (var2)
Parent: variable (var3)
Parent: constructor (contructorVar)
Child: variable (var1)
Child: initialization block (var2)
Child: variable (var3)
Child: constructor (contructorVar)
#java #initialization #static #block #constructor
Please open Telegram to view this post
VIEW IN TELEGRAM
👍10❤2❤🔥2🔥2