Careeroza
Abstract Class vs Interface
Comparison
| Abstract class | Interface | |
|---|---|---|
| Keyword | extends | implements |
| How many per class | one | many |
| Fields | any (instance state allowed) | only constants |
| Constructors | yes | no |
| Method access | any | public (private helpers allowed) |
| Use when | classes share state and code (IS-A) | unrelated classes share a capability (CAN-DO) |
| Examples | AbstractList, HttpServlet | Comparable, Runnable, List |
Rule of Thumb
Tip: Prefer interfaces for defining types (PaymentGateway, Repository). Add an abstract base class only when several implementations share real fields and code. Spring and most modern code depend on interfaces, which makes testing with mocks easy.
Functional Interfaces
An interface with exactly one abstract method is a functional interface (e.g. Runnable, Comparator). It can be implemented with a lambda. Lambdas are covered in the Advanced level.
Example
public class Main {
public static void main(String[] args) {
Greeter classic = new Greeter() { // anonymous class
public String greet(String name) { return "Hello, " + name; }
};
Greeter lambda = name -> "Namaste, " + name; // lambda
System.out.println(classic.greet("Asha"));
System.out.println(lambda.greet("Ravi"));
}
}
@FunctionalInterface
interface Greeter {
String greet(String name);
}Output
Hello, Asha Namaste, Ravi