Interfaces, Default Methods and Enums
An interface is a list of methods a class promises to have. A class can implement many interfaces.
Since Java 8, interfaces can also have default methods (with a body) and static methods.
An interface is like a contract or a job description: "anything that is a Discount must have an apply method". It says what must be done, not how. Different classes can fulfil the same contract in their own way - a flat discount, a percentage discount, a festival discount.
Code that works with the interface type (Discount d) doesn't care which class it gets. That makes programs flexible: you can add new kinds later or swap them in tests. Because a class can implement many interfaces (but extend only one class), interfaces are the main tool for designing larger Java programs. Default methods let an interface grow new methods without breaking classes that already implement it.
Enums
An enum is a fixed set of named values.
Use an enum whenever a value must be one of a small, fixed list: order status, days of the week, payment type, size (S, M, L). Compared to plain Strings, enums prevent typos ("SHIPED") because the compiler only accepts the defined values, and they work neatly with switch.
- An interface is a contract of methods; classes
implementit. - A class can implement many interfaces.
- Default methods (Java 8) give interfaces methods with a body.
- Enums are fixed sets of named values - safer than Strings.
