Commit e044125
committed
feat(lambda-vs-anonymous): implement Employee functional interface with lambda and anonymous inner class
What
- Created `Employee` as a `@FunctionalInterface` with a single abstract method `String getSalary()`.
- Implemented two different approaches in `Main.doSomething()`:
1. **Lambda Expression**
- Provides inline functional implementation of `Employee`.
- Uses a local variable (`int x = 10`) inside the lambda body.
- Accesses and modifies the outer class’s instance variable `a = 2 → 3`.
- Returns a fixed salary string `"100"`.
2. **Anonymous Inner Class**
- Provides a class-like implementation of `Employee` directly inside method scope.
- Defines its own instance variable (`int x = 10`).
- Accessed via `this.x` since `this` refers to the anonymous class instance.
- Returns `"100"` after printing its own `x`.
Why
- Demonstrates key differences between **lambda expressions** and **anonymous inner classes**:
- Lambdas are functions, not classes, so they cannot declare instance variables.
- Lambdas capture variables from the enclosing scope (`a` from outer class, `x` as local var).
- Anonymous inner classes are full classes and can declare their own instance fields (`this.x`).
- Clarifies how variable scoping and `this` resolution differ in both approaches.
Logic
1. `@FunctionalInterface` ensures only one abstract method (`getSalary()`), making it compatible with lambdas.
2. Lambda version:
- Local `x` is method-local, not tied to the class.
- Outer instance variable `a` is accessible and can be modified.
- `this` would refer to the enclosing class (`Main`).
3. Anonymous inner class version:
- Declares its own `int x` as a field.
- `this` refers to the anonymous class itself, so `this.x` resolves to its own instance variable.
4. Both implementations return the same result (`"100"`) but with different scoping and resolution behavior.
Key Takeaways
✔ `@FunctionalInterface` + lambda → concise, function-like behavior.
✔ Anonymous inner class → heavier but allows class-specific fields/methods.
✔ `this` in lambda → enclosing class.
✔ `this` in anonymous inner class → the anonymous inner class itself.
✔ Instance variable (`a`) accessible from lambda, but not from inner class unless explicitly referenced.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 7b506b7 commit e044125
File tree
1 file changed
+4
-0
lines changed- Java 8 Crash Course/Lambda Expression/Local Variable Inside Lambda Expression/src
1 file changed
+4
-0
lines changedLines changed: 4 additions & 0 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
0 commit comments