Is it possible to remove the final from the class definition, cancel backward compatibility?

I am currently reading Effective Java by Joshua Bloch, and in paragraph 17 โ€œDesign and Document for Inheritance or Prohibitionโ€. The author suggests disabling inheritance by default.

Is it safe to declare classes by default, and in a later version, delete the last keyword if you need to extend the class? Will it violate backward compatibility with code that was compiled with the previous version?

If so, it seems that a safer bet makes all classes final and removes them only in a future version if there is well-supported demand.

+6
java inheritance polymorphism final backwards-compatibility
source share
3 answers

It does not break binary or initial compatibility. This is one of the reasons why it's a good idea to make classes final; always good to change your mind about it.

The Java language specification, ยง13.4.2 , has to say about binary compatibility:

Changing the class declared final will no longer be declared final does not violate compatibility with pre-existing binaries.

I suppose that you can still make an interpreted example where it can really break the program; for example, a bytecode that generates a class, inherits a class supposedly final , and then loads that generated class and relies on receiving a VerifyError .

+10
source share

My thoughts on this:

Removing final in the class will not cause immediate problems. But consider the following:

There was the last class called AdamsFactory, which you go into is not final. Two months later, a new programmer named Dilbert joins your team.
It subclasses your class used for the final class in ScottFactory, but violates the Liskov Substitutability principle.

Then it has a ComicStripPrinter class that uses ScottFactory instead of AdamsFactory. Something will definitely break.

Which brings us back to what Joshua Block says:

If you intend to inherit: create it with a discussion and write it down. If you do not intend to inherit, then do not allow it.

I hope that what I said was not a big load.


EDIT:

Go to the introduction of the Java Langauge specification and find Joshua Bloch :)

+2
source share

If you are developing something like the Java Standard API that millions of programmers will use over the years, yes, think like Joshua Bloch. FORWARD EVOLUTION is crucial.

99% of Java programs are not. They are designed for internal use, the effect of changing the API is tiny, usually all source code is available for refactoring. SIMPLICITY is the key to such programs. If you have complex and bizarre projects, or you spend all your time thinking about the final or not, you are wasting time.

I blame Joshua for not setting proper denials of his proposals.

+2
source share

All Articles