Java-4.7 constructor initialization (1)
In this section, let's talk about the initialization of the constructor.
(1) domain initialization before the constructor Initialization
package com.ray.testobject;public class Test {private int id;public Test() {System.out.println(id:+id);id = 2;System.out.println(id:+id);}public static void main(String[] args) {new Test();}}
Output:
Id: 0
Id: 2
The output result shows that the attribute field has been initialized before the constructor.
(2) initialization order
No matter where the attribute field is put, its initialization is prior to the constructor initialization, And it is initialized in the order of arrangement.
package com.ray.testobject;public class Test {private int id;public Test() {System.out.println(id: + id);System.out.println(name: + name);System.out.println(book: + book);id = 2;name = jack;book = new Book();System.out.println(id: + id);System.out.println(name: + name);System.out.println(book: + book);}private String name;private Book book;public static void main(String[] args) {new Test();}}class Book {public Book() {System.out.println(create book);}}
Output:
Id: 0
Name: null
Book: null
Create book
Id: 2
Name: jack
Book: com. ray. testobject. Book @ c3c749
From the code above, we can see that no matter whether the attribute fields are basic types or objects, their initialization is prior to the constructor initialization, and they are initialized in an ordered order.
Before the constructor initializes, the id is initialized to 0, the name and book are objects, and the initialization is null.
Here is another example:
package com.ray.testobject;public class Test {public static void main(String[] args) {new House();}}class Window {public Window(int id) {System.out.println(create window: + id);}}class House {Window w1 = new Window(1);public House() {System.out.println(create house);w2 = new Window(99);}Window w2 = new Window(2);}
Output:
Create window: 1
Create window: 2
Create house
Create window: 99
Summary: This section describes the initialization sequence of the constructor.
This chapter is here. Thank you.