Commit e4f5ef9
committed
feat: Add Shadowing class to demonstrate variable shadowing in Java
WHAT the code does:
- Defines a class `Shadowing` with a static class variable `x = 90`.
- In `main()`, declares a local variable `x` that **shadows** the class variable.
- Prints the class-level `x` before shadowing, then prints the local `x` after initialization.
- Includes a `fun()` method that prints the class-level `x` (since local `x` is not in scope there).
WHY this matters:
- Demonstrates the concept of **variable shadowing** in Java:
- A local variable can hide a class or outer scope variable with the same name.
- Helps understand scope resolution in Java.
- Highlights why naming conventions are important to avoid confusion.
HOW it works:
1. Prints static `x = 90` before local `x` is declared.
2. Declares local `x`, then assigns `40`.
3. Prints local `x = 40`, which hides the class variable within `main()`.
4. Calls `fun()` → prints static `x = 90` because local shadowing does not apply there.
Tips & gotchas:
- Declaring but not initializing a local variable (`int x;`) prevents usage until assigned → attempting `System.out.println(x)` before initialization would cause a compile error.
- Shadowing does not delete the outer variable; it just makes it inaccessible in that scope.
- Avoid variable shadowing in production code for clarity — prefer distinct names.
- Can use `ClassName.variable` or `this.variable` (for instance vars) to access shadowed variables explicitly.
Use-cases:
- Educational demonstration of **scope and shadowing**.
- Helps in debugging when multiple variables with the same name cause unexpected behavior.
- Foundation for understanding **lexical scope** and variable lifetime in Java.
Short key: class-shadowing-static-local.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent cef67ee commit e4f5ef9
1 file changed
+8
-4
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | | - | |
| 2 | + | |
| 3 | + | |
3 | 4 | | |
4 | 5 | | |
5 | | - | |
6 | | - | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
7 | 12 | | |
8 | 13 | | |
9 | 14 | | |
10 | 15 | | |
11 | | - | |
12 | 16 | | |
13 | 17 | | |
14 | 18 | | |
| |||
0 commit comments