7) Interfaces & Abstract Classes
Goal
Use interfaces for capabilities and abstraction; understand abstract classes and when they fit.
Interfaces
interface Payable {
long calculatePayCents();
}
class Contractor implements Payable {
private final long hourlyRateCents;
private final int hours;
Contractor(long hourlyRateCents, int hours) {
this.hourlyRateCents = hourlyRateCents;
this.hours = hours;
}
public long calculatePayCents() {
return hourlyRateCents * hours;
}
}
Abstract classes
Use when you want shared code + some required methods:
abstract class Employee {
protected final String name;
protected Employee(String name) {
this.name = name;
}
abstract long calculatePayCents();
}
Practical guideline
- Use interfaces for public APIs and “capabilities”.
- Use abstract classes for shared implementation inside a family of classes.
Exercises
- Create
Storage interface with methods save(String key, String value) and load(String key).
- Implement it with an in-memory
MapStorage.
Table of contents
- Getting Started: Install, run, and your first program
- Java Basics: types, variables, operators, formatting
- Control Flow: if/switch/loops
- Methods: parameters, return values, overloading
- OOP: classes, objects, encapsulation
- Inheritance & Polymorphism (and when not to use them)
- Interfaces, abstract classes, and design basics
- Exceptions and error handling
- Strings, files, and I/O basics
- Collections: List/Set/Map and Big-O intuition
- Generics (the useful parts)
- Lambdas & Streams
- Dates and time (java.time)
- Testing with JUnit 5 (basics)
- Concurrency: threads, executors, futures
- JVM basics: memory, GC, performance habits
- Build tools: Maven essentials (recommended)
- Next steps: projects to build