kolejność wywołań konstruktora w dziedziczeniu wielopoziomowym w java [duplikat]
To pytanie ma już odpowiedź tutaj:
Java Constructors - Kolejność wykonywania w hierarchii dziedziczenia 5 odpowiedzi//: c07:Sandwich.java
// Order of constructor calls.
// package c07;
// import com.bruceeckel.simpletest.*;
import java.util.*;
class Meal {
Meal() { System.out.println("Meal()"); }
}
class Bread {
Bread() { System.out.println("Bread()"); }
}
class Cheese {
Cheese() { System.out.println("Cheese()"); }
}
class Lettuce {
Lettuce() { System.out.println("Lettuce()"); }
}
class Lunch extends Meal {
Lunch() { System.out.println("Lunch()"); }
}
class PortableLunch extends Lunch {
PortableLunch() { System.out.println("PortableLunch()");}
}
public class Sandwich extends PortableLunch {
// private static Test monitor = new Test();
private Bread b = new Bread();
private Cheese c = new Cheese();
private Lettuce l = new Lettuce();
public Sandwich() {
System.out.println("Sandwich()");
}
public static void main(String[] args) {
new Sandwich();
/*
monitor.expect(new String[] {
"Meal()",
"Lunch()",
"PortableLunch()",
"Bread()",
"Cheese()",
"Lettuce()",
"Sandwich()"
});
// */
}
} ///:~
Wynik tego kodu to
Meal()
Lunch()
PortableLunch()
Bread()
Cheese()
Lettuce()
Sandwich()
Ponieważ pola w klasie są tworzone w kolejności ich zadeklarowania, dlaczego nie
Bread()
Cheese()
Lettuce()
come na górze powyższej listy?
Również co próbuje zrobić w tym kodzie?
monitor.expect(new String[] {
"Meal()",
"Lunch()",
"PortableLunch()",
"Bread()",
"Cheese()",
"Lettuce()",
"Sandwich()"
});
Na początku myślałem, że to anonimowa klasa, ale tak nie wygląda. Czy inicjuje tablicę String? Dlaczego nie ma nazwy zmiennej String? Proszę podać nazwę używanego tutaj konstruktu programistycznego.