Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 90

Following the Order of Initialization

Оглавление

When writing code that initializes fields in multiple places, you have to keep track of the order of initialization. This is simply the order in which different methods, constructors, or blocks are called when an instance of the class is created. We add some more rules to the order of initialization in Chapter 6. In the meantime, you need to remember:

 Fields and instance initializer blocks are run in the order in which they appear in the file.

 The constructor runs after all fields and instance initializer blocks have run.

Let's look at an example:

1: public class Chick { 2: private String name = "Fluffy"; 3: { System.out.println("setting field"); } 4: public Chick() { 5: name = "Tiny"; 6: System.out.println("setting constructor"); 7: } 8: public static void main(String[] args) { 9: Chick chick = new Chick(); 10: System.out.println(chick.name); } }

Running this example prints this:

setting field setting constructor Tiny

Let's look at what's happening here. We start with the main() method because that's where Java starts execution. On line 9, we call the constructor of Chick. Java creates a new object. First it initializes name to "Fluffy" on line 2. Next it executes the println() statement in the instance initializer on line 3. Once all the fields and instance initializers have run, Java returns to the constructor. Line 5 changes the value of name to "Tiny", and line 6 prints another statement. At this point, the constructor is done, and then the execution goes back to the println() statement on line 10.

Order matters for the fields and blocks of code. You can't refer to a variable before it has been defined:

{ System.out.println(name); } // DOES NOT COMPILE private String name = "Fluffy";

You should expect to see a question about initialization on the exam. Let's try one more. What do you think this code prints out?

public class Egg { public Egg() { number = 5; } public static void main(String[] args) { Egg egg = new Egg(); System.out.println(egg.number); } private int number = 3; { number = 4; } }

If you answered 5, you got it right. Fields and blocks are run first in order, setting number to 3 and then 4. Then the constructor runs, setting number to 5. You see a lot more rules and examples covering order of initialization in Chapter 6. We only cover the basics here so you can follow the order of initialization for simple programs.

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

Подняться наверх