Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Circumstances to make a class final? [closed]

Tags:

java

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??

like image 565
user997112 Avatar asked Jul 30 '12 22:07

user997112


People also ask

Why would you want to make an entire class final?

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.

When should a class be declared final?

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.

Can a class be made final?

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.

How do you declare a class as final?

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 { . . . }


1 Answers

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".

like image 160
assylias Avatar answered Sep 25 '22 05:09

assylias