These notes recap Topic 3.8. For worked examples, read the study guide.
Recap
- A local variable is declared in the header or body of a block and can be used only in that block.
- Constructors and methods are blocks, so their parameters are local variables. They cannot be declared
publicorprivate. - Instance and class variables are in scope throughout the class.
public/privatedecide access from other classes. - If a local variable or parameter has the same name as an instance variable, the name refers to the local one inside that constructor or method.
name = name;in a constructor assigns the parameter to itself and leaves the instance variable at its default.
Key relationships
| Variable kind | Declared | Visible | Access modifier? |
|---|---|---|---|
| Instance variable | In the class, outside methods | Whole class; others by access | Yes |
| Class variable | In the class with static |
Whole class; others by access | Yes |
| Parameter | In a method or constructor header | That method or constructor | No |
| Local variable | In a method, constructor or inner block | That block, after its declaration | No |
| Loop variable | In a for header |
The loop only | No |
Worked reminder
For class Calc with private int x = 2; and calc(int y): calc(1) has z = 3 and skips the if, returning 3; calc(4) has z = 6, enters the if, makes w = 12 and returns 12. For Pet(String name, int age) { name = name; age = age; } the object prints null 0. For Scorer with total 7, a method whose parameter is also named total returns 25 and leaves the object’s total at 7.
Reading scope in the exam
Underline each declaration and draw a bracket from it to the closing brace of its block. A use of the name outside the bracket is a compile error. When a parameter and an instance variable share a name, cross out the instance variable inside that method: the name now means the parameter, and a change to it never reaches the object.
Compile errors to recognise
| Message | Typical cause |
|---|---|
cannot find symbol (variable) |
Used outside its block, in another method, or never declared |
| (no error, wrong output) | A parameter or local variable hides an instance variable |
Mistakes to avoid
- Using a loop variable after the loop.
- Declaring a variable inside an
ifand using it after theif. - Naming a constructor parameter the same as an instance variable and writing
x = x;. - Re-declaring an instance variable inside a method when you meant to change it (
int total = ...instead oftotal = ...). - Believing a local variable can be public or private.
Quick self-check
- Where can a variable declared in a
forheader be used? Answer: only in that loop. - A method has
int count = 0;and the class also has an instance variablecount. Which doescount++change? Answer: the local variable. - What does
new Pet("Rex", 4).describe()print for the buggy constructor withname = name;? Answer:null 0. - Can a parameter be declared
private? Answer: No.