When to prevent class inheritance?

I was recently told about good practice in object-oriented programming, which should always allow inheritance from your classes . I really don't think so, but I have no solid arguments.

Real examples of blocked inheritance :

  • No C ++ STL class (specialized template template) allows inheritance (with non-virtual destructors).
  • Java has a class modifier finalthat applies to many standard components, for example java.lang.String.

Possible reasons I think:

  • Security , as a subclass can have access to sensitive internal elements. (I don’t think so - they will not have access to private members.)
  • Performance , because a subclass can ruin our efficient implementations by overriding some of the member functions. (Children will not override non-virtual functions.)
  • To provide composition over inheritance . (I completely agree. We should not approve inheritance when it is not needed.)

So my question is: In what circumstances do I intentionally block inheritance?

+5
source share
3 answers

, , , " Java", , : , , , .

" Java" ( ) , .

. ( ), , . , , .

+3

, , , , . (, ) , , , final.

, , :

  • , , . , , , / , .

  • . final, . , String, , String. , String, , .

  • . , (.. , ).

  • . , , Java . , , , inline . , , , , ( ).

+4

0,02 ...

Enabling inheritance for a class allows people to cope with unforeseen problems. (for example, monkeypatching, which is often found in RoR. It may be ugly, but it is a reality against pedantry). Having said that, I am not a big fan of gratuitous inheritance. The relationship between the base and subclasses can be fragile. Deep hierarchies of inheritance are hard to find.

In one case, I can think of prohibiting inheritance - it is forced immutability. This is important for things like the Java String class.

+3
source

All Articles