Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you make a whole class sealed/final?

I understand the motivation for making individual methods of a class sealed/final, but what purpose does completely prohibiting inheritance from the class serve? While allowing overriding of certain methods can cause bad things to happen, I can't see how allowing inheritance from your class purely to add behavior to it without overriding existing behavior could ever be a bad thing. If you really want to disallow overriding anything in your class, why not just make every method final but still allow inheritance for the purpose of adding behavior?

like image 276
dsimcha Avatar asked Feb 03 '23 06:02

dsimcha


2 Answers

There are some good discussions about this in the "Why String is final in Java" question: Why is String class declared final in Java?

The basic summary in that case is, String is immutable, and if it could be subclassed, the subclass might make it mutable.

like image 117
Ray Hidayat Avatar answered Feb 20 '23 19:02

Ray Hidayat


An organisation/software dev team might want to enforce certain coding standards. For example, in order to improve readability, they might only want attribute X of class Y to be modified with method Z and nothing else. If the class were not final, some developer might extend class Y and add method W, which could modify X in a different way and cause confusion and delay when it came to comprehending the code written.

like image 23
Jimmeh Avatar answered Feb 20 '23 17:02

Jimmeh