Open-closed principle and Java “final” modifier

后端 未结 7 1216
灰色年华
灰色年华 2020-12-29 04:37

The open-closed principle states that \"Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification\".

However, J

7条回答
  •  一整个雨季
    2020-12-29 05:15

    The two statements

    Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.

    and

    Design and document for inheritance, or else prohibit it.

    are not in direct contradiction with one another. You can follow the open-closed principle as long as you design and document for it (as per Bloch's advice).

    I don't think that Bloch states that you should prefer to prohibit inheritance by using the final modifier, just that you should explicitly choose to allow or disallow inheritance in each class you create. His advice is that you should think about it and decide for yourself, instead of just accepting the default behavior of the compiler.

提交回复
热议问题