Are there any general guidelines as to when to make a class final?
I thought it was if you did not want people extending your class, but that seems slightly.... naive??
The main purpose of using a class being declared as final is to prevent the class from being subclassed. If a class is marked as final then no class can inherit any feature from the final class. You cannot extend a final class.
Final classes are ones that cannot be inherited from, which means it's not possible for users of your code to add functionality or change what they have. This is not the default: you must opt in to this behavior by adding the final keyword to your class.
Note that you can also declare an entire class final. A class that is declared final cannot be subclassed. This is particularly useful, for example, when creating an immutable class like the String class.
To specify that your class is a final class, use the keyword final before the class keyword in your class declaration. For example, if you wanted to declare your (perfect) ChessAlgorithm class as final, its declaration would look like this: final class ChessAlgorithm { . . . }
Making a class final only prevents it from being extended as you note. Why would you want to do that?
One typical use case is to guarantee immutability. If you design an immutable class but don't make it final, it can be extended in a mutable way. This can in turn lead to a subclass corrupting a class invariant or creating concurrency issues.
You could also simply mark a class as final to document the fact that it is not designed to be extended. See for example Effective Java #17: "Design and document for inheritance or else prohibit it".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With