Skip to content

Commit e4f5ef9

Browse files
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

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

Section10Methods/Methods 2.O/src/Shadowing.java

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,18 @@
11
public class Shadowing {
2-
static int x = 90; // this will be shadowed at line 8
2+
static int x = 90; // this will be shadowed at line 12.
3+
34
public static void main(String[] args) {
45
System.out.println(x); // 90
5-
int x; // the class variable at line 4 is shadowed by this
6-
// System.out.println(x); // scope will begin when value is initialised
6+
7+
int x;
8+
// the class variable at line 2 is shadowed by this.
9+
// System.out.println(x);
10+
// scope will begin when value is initialised
11+
712
x = 40;
813
System.out.println(x); // 40
914
fun();
1015
}
11-
1216
static void fun() {
1317
System.out.println(x);
1418
}

0 commit comments

Comments
 (0)