Commit 0f8d6a2
committed
feat(static-methods-in-interfaces): demonstrate static main method in class and interface
What
- Added `MyClass` with a standard `public static void main` method that prints "Hello".
- Added `MyInterface` containing its own `public static void main` method:
- Proves that static methods (including `main`) are allowed inside interfaces (Java 8+).
- Both can be executed independently:
- `MyClass.main()` → prints "Hello".
- `MyInterface.main()` → prints "Hello".
Why
- Java 8 introduced static methods in interfaces to support utility-like behaviors.
- Demonstrates that interfaces are no longer restricted to abstract contracts only; they can now also:
- Host reusable helper methods.
- Contain entry points (main method) for testing or running logic.
Logic
1. `MyClass`:
- Regular class with `main` method → standard entry point.
2. `MyInterface`:
- Declares a static `main` method.
- Unlike default methods, static methods in interfaces are **not inherited** by implementing classes.
- They must be called via the interface name.
Real-life applications
- Interfaces can define **static utility methods** (e.g., `Comparator.naturalOrder()`, `Collections.emptyList()`).
- Useful for grouping helper logic directly inside the interface, avoiding separate utility classes.
- Adding `main` inside an interface is occasionally used for:
- Quick testing/demo of interface behavior.
- Running small examples without creating extra classes.
Notes
- Static methods in interfaces:
- Cannot be overridden by implementing classes.
- Must be called with the interface name, not via instance.
- Demonstrates flexibility added in Java 8 for backward compatibility and reducing boilerplate.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 6894ea4 commit 0f8d6a2
File tree
1 file changed
+7
-0
lines changed- Java 8 Crash Course/Functional Interface/Static Methods/src/Package
1 file changed
+7
-0
lines changedLines changed: 7 additions & 0 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
0 commit comments