Abstract Class vs Interface

Comparison

Abstract classInterface
Keywordextendsimplements
How many per classonemany
Fieldsany (instance state allowed)only constants
Constructorsyesno
Method accessanypublic (private helpers allowed)
Use whenclasses share state and code (IS-A)unrelated classes share a capability (CAN-DO)
ExamplesAbstractList, HttpServletComparable, 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