Practical Use Cases for Local Classes
You'll learn: When local classes are the cleanest solution for real-world Java problems.
The Right Tool for the Right Job
Local classes shine when you need a helper class for complex logic within a single method, especially when that helper needs access to local variables or method parameters. They keep implementation details encapsulated right where they're used, avoiding namespace pollution.
Real-World Scenarios
Sorting with Custom Logic
When you need a one-time Comparator that depends on method parameters:
public void sortByDistance(List<City> cities, City reference) {
class DistanceComparator implements Comparator<City> {
public int compare(City c1, City c2) {
double d1 = reference.distanceTo(c1);
double d2 = reference.distanceTo(c2);
return Double.compare(d1, d2);
}
}
cities.sort(new DistanceComparator());
}
The comparator needs reference (effectively final), and you'll never use it outside this method. Perfect for a local class.
Filtering with Stateful Predicates
When filtering logic needs to accumulate state:
public List<String> findDuplicates(List<String> items) {
class DuplicateFilter {
Set<String> seen = new HashSet<>();
boolean isDuplicate(String item) {
return !seen.add(item);
}
}
DuplicateFilter filter = new DuplicateFilter();
List<String> result = new ArrayList<>();
for (String item : items) {
if (filter.isDuplicate(item)) {
result.add(item);
}
}
return result;
}
Iterator Implementations
Creating custom iterators that need access to the collection's state.
Why Not Alternatives?
- Anonymous class: Too verbose for multiple methods or fields
- Nested class: Overkill if only one method needs it
- Top-level class: Pollutes namespace for single-use logic
Key Takeaway: Use local classes when you need a named helper class with state or multiple methods that depends on method-local context—they keep complex logic organized without exposing unnecessary implementation details.