The output shows that the instance initialization clause is executed before either one of the constructors.
// housekeeping/Mugs.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Instance initialization
class Mug {
Mug(int marker) {
System.out.println("Mug(" + marker + ")");
}
}
public class Mugs {
Mug mug1;
Mug mug2;
{ // [1]
mug1 = new Mug(1);
mug2 = new Mug(2);
System.out.println("mug1 & mug2 initialized");
}
Mugs() {
System.out.println("Mugs()");
}
Mugs(int i) {
System.out.println("Mugs(int)");
}
public static void main(String[] args) {
System.out.println("Inside main()");
new Mugs();
System.out.println("new Mugs() completed");
new Mugs(1);
System.out.println("new Mugs(1) completed");
}
}
/* Output:
Inside main()
Mug(1)
Mug(2)
mug1 & mug2 initialized
Mugs()
new Mugs() completed
Mug(1)
Mug(2)
mug1 & mug2 initialized
Mugs(int)
new Mugs(1) completed
*/
ps: blank lines in comments are used to highlight constructor initialize oder.
change [1] code and its location, the code like:
// housekeeping/Mugs.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Instance initialization
class Mug {
Mug(int marker) {
System.out.println("Mug(" + marker + ")");
}
}
public class Mugs {
Mug mug3;
Mug mug4;
Mugs() {
System.out.println("Mugs()");
}
{ // [1]
mug3 = new Mug(3);
mug4 = new Mug(4);
System.out.println("mug3 & mug4 initialized");
}
Mugs(int i) {
System.out.println("Mugs(int)");
}
public static void main(String[] args) {
System.out.println("Inside main()");
new Mugs();
System.out.println("new Mugs() completed");
new Mugs(1);
System.out.println("new Mugs(1) completed");
}
}
/* My Output:
Inside main()
Mug(3)
Mug(4)
mug3 & mug4 initialized
Mugs()
new Mugs() completed
Mug(3)
Mug(4)
mug3 & mug4 initialized
Mugs(int)
new Mugs(1) completed
*/
for better understand, please read below content.
see static explicit data initialization.
see initialization with inheritance.
references:
1. On Java 8 - Bruce Eckel
2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/housekeeping/Mugs.java