Код: Выделить всё
package pkg;
public class LoadTest {
public static void main(String[] args) {
System.out.println("START");
new Child();
System.out.println("END");
}
}
class Parent extends Grandparent {
// Instance init block
{
System.out.println("instance - parent");
}
// Constructor
public Parent() {
System.out.println("constructor - parent");
}
// Static init block
static {
System.out.println("static - parent");
}
}
class Grandparent {
// Static init block
static {
System.out.println("static - grandparent");
}
// Instance init block
{
System.out.println("instance - grandparent");
}
// Constructor
public Grandparent() {
System.out.println("constructor - grandparent");
}
}
class Child extends Parent {
// Constructor
public Child() {
System.out.println("constructor - child");
}
// Static init block
static {
System.out.println("static - child");
}
// Instance init block
{
System.out.println("instance - child");
}
}
START
static - дедушка
static - родитель
статический - дочерний экземпляр
экземпляр - дедушка
конструктор - дедушка
экземпляр - родительский
конструктор - родительский
экземпляр - дочерний
конструктор - дочерний
END
Очевидный ответ заключается в том, что блоки родителей выполняются раньше блоков их детей, но это может быть просто совпадением и не поможет, если два класса не принадлежат одному и тому же иерархия.
РЕДАКТИРОВАТЬ:
Я изменил свой пример кода, добавив его в LoadTest.java:
Код: Выделить всё
class IAmAClassThatIsNeverUsed {
// Constructor
public IAmAClassThatIsNeverUsed() {
System.out.println("constructor - IAACTINU");
}
// Instance init block
{
System.out.println("instance - IAACTINU");
}
// Static init block
static {
System.out.println("static - IAACTINU");
}
}
Подробнее здесь: https://stackoverflow.com/questions/200 ... n-java-run
Мобильная версия