Сначала вызываются все статические блоки в очередности от первого статического блока корневого предка и выше по цепочке иерархии до статических блоков самого класса.
Затем вызываются нестатические блоки инициализации корневого предка, конструктор корневого предка и так далее вплоть до нестатических блоков и конструктора самого класса.
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
Конструктор по умолчанию (Default Constructor)
Это конструктор без параметров, который автоматически создается компилятором, если в классе не объявлено ни одного конструктора. Он будет пустым и не делает ничего, кроме вызова конструктора суперкласса.
public class MyClass {
private int number;
private String text;
// Компилятор создаст конструктор по умолчанию:
// public MyClass() {
// super();
// }
}
Конструктор с параметрами (Parameterized Constructor)
Это конструктор, который принимает один или несколько параметров, используемых для инициализации полей класса. Если объявлен хотя бы один конструктор с параметрами, конструктор по умолчанию больше не создается автоматически (его нужно явно определить, если он нужен).
public class MyClass {
private int number;
private String text;
public MyClass(int number, String text) {
this.number = number;
this.text = text;
}
}
Конструктор копирования (Copy Constructor)
Это конструктор, который создает новый объект как копию существующего объекта того же класса.
public class MyClass {
private int number;
private String text;
// Конструктор копирования
public MyClass(MyClass other) {
this.number = other.number;
this.text = other.text;
}
}
#java #constructor
Please open Telegram to view this post
VIEW IN TELEGRAM
👍8❤3🔥1👨💻1