且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我什么时候应该使用"final"?

更新时间:2022-12-08 10:33:27

它可以防止其他程序员处理您不希望他们从事的工作.因此,与其发表评论说不要使用此类来做XXX",您可以以这样一种方式设计它:他们不会被诱惑覆盖它并以这种方式滥用它.

It prevents other programmers from doing stuff with your classes that you don't intend for them to do. So rather than making a comment saying "don't use this class to do XXX", you can design it in such a way that they won't be tempted to override it and abuse it in that manner.

编辑:由于请求了一个示例,因此我将描述一种情况,在这种情况下,您可能会发现此关键字很方便……说您有一个定义两个对象如何相互通信的类,例如,一个侦听器和通知者.侦听器类显然必须允许继承,但是您可能希望将通告程序类定为最终类,以便必须以"has-a"关系使用它.这样,您可以从侦听器对象中对接收到的消息的性质进行一些假设.

Edit: Since an example is requested, I'll describe a case where you might find this keyword handy... say you have a class which defines how two objects may communicate with each other, say, a listener and notifier. The listener class must obviously allow inheritance, but you might want to make the notifier class final so that it must be used in a "has-a" relationship. This way, you can make some assumptions from your listener objects about the nature of the messages they are receiving.

否则,将有可能从该类继承,做各种疯狂的事情,例如扩展消息等等.如果您不希望其他程序员那样做,则可以将类定型.另外,在广泛使用的公共API中,这可能更有意义,因为它还使其他程序员可以容易地理解哪些类可以作为子类.

Otherwise, it would be possible to inherit from that class, do all sorts of crazy stuff like extend the messages and so on. If you don't want other programmers to do that, then you could make the class final. Also, this might make a lot more sense in a widely-used public API, as it also allows other programmers to readily understand which classes are ok to subclass.

另一个例子-假设您有一个基于缓冲区的流处理器,并且在read()/write()方法内部,维护了一些有关对象当前状态的数据(即,当前字节或其他内容) .没有办法保证在处理过程中任何此类的子类都将调用super的方法-并且由于此类可能仅包含几个方法,因此***使整个事情成为最终方法,而不是使每个方法都成为最终方法.这再次迫使使用该类的人拥有"而不是具有",因此可以控制您期望代码将如何执行.

Another example -- say you have a buffer-based stream processor, and inside of your read()/write() method, you maintain some data about the current state of your object (ie, the current byte or whatever). There is no way to guarantee that anyone subclassing this class would call the super's methods during processing -- and since such a class likely only contains a few methods, it's better to just make the whole thing final instead of each method. This again forces people using the class to "has-a", not "is-a", and thus, can control how you expect the code will be executed.

我会同意您的观点,即完成整个 class 决赛可能是您需要在一次蓝月亮中做一次的事情,但是很高兴PHP具有此功能,如果您选择锻炼它.

I would agree with you in that making an entire class final is probably something which you'd need to do once in a blue moon, but it's nice that PHP has this capability should you choose to exercise it.