Search code examples
javainheritancepolymorphismbackwards-compatibilityfinal

Can removing final from a class definition break backwards compatibility?


I'm currently reading Effective Java by Joshua Bloch and Item 17 is 'Design and document for inheritance or else prohibit it'. The author suggest to prohibit inheritance by default.

Is it safe to declare classes final by default and in a later release remove the final keyword if there is a need to extend the class? Will it break backwards compatibility against code that was compiled with a previous version?

If so it appears that it is a safer bet to make all classes final and only remove it in a future release if there is a well supported demand.


Solution

  • It breaks neither binary nor source compatibility. That's one of the reasons it's a good idea to make classes final; it's always OK to change your mind about it.

    The Java Language Specification, §13.4.2, has the following to say about binary compatibility:

    Changing a class that was declared final to no longer be declared final does not break compatibility with pre-existing binaries.

    I suppose you still could make up a construed example where it actually could break a program; like bytecode-generating a class inheriting from the supposedly final class, and then loading that generated class and relying on getting a VerifyError.