Skip to content

Commit f777d9a

Browse files
committed
feat(anonymous-inner-class): implement Employee interface using anonymous inner class
What - Defined `Employee` interface with two abstract methods: `getSalary()` and `getType()`. - Created `SoftwareEngineer` class as a concrete implementation of `Employee`. - Added `Main` class demonstrating: - Anonymous inner class implementing `Employee` directly inside `main()`. - Overridden methods `getSalary()` and `getType()` inline without needing a separate file. - Printed salary and type information to console. Why - Showcases how to use **anonymous inner classes** when you want one-time implementation of an interface. - Highlights limitation: cannot use **lambda expressions** here because `Employee` has **two abstract methods**, making it a functional interface violation. - Simplifies code by removing the need for a dedicated concrete class when implementation is small and used only once. Logic 1. `Employee` interface: - Declares two abstract methods. - Any class implementing it must provide concrete definitions. 2. `SoftwareEngineer` class: - Full implementation of `Employee`, reusable in multiple places. 3. `Main` class: - Demonstrates anonymous inner class: - Declares `Employee E = new Employee() { ... }`. - Provides inline implementation of `getSalary()` and `getType()`. - Calls both methods and prints results. - Notes: - Cannot instantiate an interface directly (`new Employee()` not possible without implementation). - Anonymous inner class is created **on the fly** without a named class file. - Lambda not possible since `Employee` is not a functional interface (it has 2 abstract methods). Real-life applications - Quick prototypes when you need only one-off implementation of an interface. - Event handling (e.g., `ActionListener` in Swing GUI). - Thread creation before Java 8 (using `Runnable` as anonymous inner class). - Avoiding boilerplate class creation for small, single-use logic. Notes - If only one abstract method existed in `Employee`, it could be marked as a **functional interface** and replaced with a lambda. - Anonymous inner classes can access enclosing method variables if they are effectively final. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 366ea63 commit f777d9a

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package Package;
2+
3+
public class SoftwareEngineer implements Employee {
4+
@Override
5+
public String getSalary() {
6+
return "10 LPA";
7+
}
8+
9+
@Override
10+
public String getType() {
11+
return "Software Engineer";
12+
}
13+
}

0 commit comments

Comments
 (0)