Video in progress

Strong Junior 🧱 OOP and SOLID

When is it appropriate to make a class or a method `final`?

A final class can't be inherited from, and a final method can't be overridden. They are used when the class isn't designed for inheritance, or when you need an immutability or security guarantee.

📖 Answer

String, Integer, LocalDate are all final. If you could extend String and break equals, HashMap keys and security checks would be unreliable.

When I make something final:

  • an immutable class, so a child class can't add a mutable field and break the guarantee;
  • a class not designed for inheritance: if internal methods call each other, overriding them gives unexpected results;
  • a template method: the skeleton of the algorithm shouldn't change, and only the "hole" methods are open.
public abstract class Report {
    public final String render() {   // the order is fixed
        return header() + body() + footer();
    }
    protected abstract String body();
    protected String header() { return ""; }
    protected String footer() { return ""; }
}

One trap: Spring and Hibernate create a subclass for proxies. On a @Transactional bean with a final class or a final method, the proxy doesn't work or the method is bypassed. That is why Kotlin has the allopen plugin. Records, on the other hand, are automatically final.