Skip to the page

Objects and language basics · core

final, finally, static and interface rules

The keywords final, finally and static each have a precise meaning. Default methods in interfaces can clash, and then the class must choose.

The notes

What you must know

  • final variable: assigned once. The reference is fixed, but the object can still change. final method: cannot be overridden. final class: cannot be extended.
  • finally runs after try and catch whether or not an exception happened. It does not run if the JVM exits (System.exit, a crash or kill -9).
  • finalize is an old hook run by the GC with no guarantee about when or if. It is deprecated for removal. Use try-with-resources or a Cleaner.
  • static belongs to the class. Static methods are hidden, not overridden: the call depends on the declared type. Static blocks run once when the class is initialised.
  • Static mutable state is shared by every request thread: races and data leaking between users. Static collections are also GC roots, so they can leak memory.
  • Two interfaces with the same default method give a compile error in the class that implements both. Fix it by overriding and choosing: Notifier.super.channel().
  • Resolution rules: a method from the class hierarchy beats an interface default; a more specific sub-interface beats its parent; otherwise the class must decide.
  • Default methods let library authors add methods without breaking every implementation. An abstract class can hold instance state and constructors; an interface cannot.

The red pen

Common traps: mistake → fix

  • Mistake: final makes an object immutable

    Fix: final only stops reassigning the variable.

  • Mistake: finally always runs

    Fix: not after System.exit or a JVM crash.

  • Mistake: A static method can be overridden

    Fix: it is hidden; the declared type decides which one runs.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is the difference between final, finally and finalize?
  2. What does static mean on a field, a method and a block?
  3. Will this class compile if it implements two interfaces with the same default method?
  4. When would you choose an abstract class over an interface?

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview