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

Executing Instance Initializer Blocks

Оглавление

When you learned about methods, you saw braces ({}). The code between the braces (sometimes called “inside the braces”) is called a code block. Anywhere you see braces is a code block.

Sometimes code blocks are inside a method. These are run when the method is called. Other times, code blocks appear outside a method. These are called instance initializers. In Chapter 6, you learn how to use a static initializer.

How many blocks do you see in the following example? How many instance initializers do you see?

1: public class Bird { 2: public static void main(String[] args) { 3: { System.out.println("Feathers"); } 4: } 5: { System.out.println("Snowy"); } 6: }

There are four code blocks in this example: a class definition, a method declaration, an inner block, and an instance initializer. Counting code blocks is easy: you just count the number of pairs of braces. If there aren't the same number of open ({) and close (}) braces or they aren't defined in the proper order, the code doesn't compile. For example, you cannot use a closed brace (}) if there's no corresponding open brace ({) that it matches written earlier in the code. In programming, this is referred to as the balanced parentheses problem, and it often comes up in job interview questions.

When you're counting instance initializers, keep in mind that they cannot exist inside of a method. Line 5 is an instance initializer, with its braces outside a method. On the other hand, line 3 is not an instance initializer, as it is only called when the main() method is executed. There is one additional set of braces on lines 1 and 6 that constitute the class declaration.

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

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