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

Limiting Scope

Оглавление

Local variables can never have a scope larger than the method they are defined in. However, they can have a smaller scope. Consider this example:

3: public void eatIfHungry(boolean hungry) { 4: if (hungry) { 5: int bitesOfCheese = 1; 6: } // bitesOfCheese goes out of scope here 7: System.out.println(bitesOfCheese); // DOES NOT COMPILE 8: }

The variable hungry has a scope of the entire method, while the variable bitesOfCheese has a smaller scope. It is only available for use in the if statement because it is declared inside of it. When you see a set of braces ({}) in the code, it means you have entered a new block of code. Each block of code has its own scope. When there are multiple blocks, you match them from the inside out. In our case, the if statement block begins at line 4 and ends at line 6. The method's block begins at line 3 and ends at line 8.

Since bitesOfCheese is declared in an if statement block, the scope is limited to that block. When the compiler gets to line 7, it complains that it doesn't know anything about this bitesOfCheese thing and gives an error.

Remember that blocks can contain other blocks. These smaller contained blocks can reference variables defined in the larger scoped blocks, but not vice versa. Here's an example:

16: public void eatIfHungry(boolean hungry) { 17: if (hungry) { 18: int bitesOfCheese = 1; 19: { 20: var teenyBit = true; 21: System.out.println(bitesOfCheese); 22: } 23: } 24: System.out.println(teenyBit); // DOES NOT COMPILE 25: }

The variable defined on line 18 is in scope until the block ends on line 23. Using it in the smaller block from lines 19 to 22 is fine. The variable defined on line 20 goes out of scope on line 22. Using it on line 24 is not allowed.

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

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