你为什么要把全班密封/最终? [英] Why would you make a whole class sealed/final?

查看:79
本文介绍了你为什么要把全班密封/最终?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解制作类密封 / 最终的个别方法的动机,但是完全禁止的目的是什么从班级继承服务?虽然允许覆盖某些方法可能会导致不好的事情发生,但我无法看到如何允许从类中继承纯粹为了在不覆盖现有行为的情况下向其添加行为,这可能是件坏事。如果你真的想要禁止在你的类中覆盖任何东西,为什么不只是让每个方法都最终但仍然允许继承以便添加行为?

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?

推荐答案

组织/软件开发团队可能希望强制执行某些编码标准。例如,为了提高可读性,他们可能只希望使用方法Z修改类Y的属性X而不是其他任何东西。如果类不是最终的,那么一些开发人员可能会扩展类Y并添加方法W,这可能会以不同的方式修改X,并在理解所编写的代码时引起混淆和延迟。

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.

这篇关于你为什么要把全班密封/最终?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆