为什么java.util.Scanner类声明为'final'? [英] Why is the java.util.Scanner class declared 'final'?

查看:192
本文介绍了为什么java.util.Scanner类声明为'final'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用扫描仪课程用于读取多个类似文件。我想扩展它以确保它们都使用相同的分隔符,我还可以添加所有对它们都有效的 skipUntilYouFind(String thisHere)等方法。



我可以创建一个包含它们的实用程序类,或者将Scanner类作为变量嵌入到另一个类中,但这更麻烦。



我发现某些原因声明一个类final,但为什么要在这里完成?

解决方案

可能因为扩展它并覆盖它的一些方法可能会破坏它。并且更容易覆盖方法会暴露大部分内部工作,因此如果将来他们决定改变那些(出于性能或其他原因),他们将更难以在不破坏所有类的情况下更改类扩展它。



例如,考虑类中的以下方法:

  public boolean nextBoolean(){
clearCaches();
返回Boolean.parseBoolean(next(boolPattern()));
}

假设你要覆盖这个,因为你想让'awesome'评价到'true'布尔值(无论出于何种原因)。如果覆盖它,则无法调用super.nextBoolean(),因为这会使用默认逻辑消耗下一个标记。但是如果不调用super.nextBoolean(),则不会调用clearCaches(),可能会破坏其他未覆盖的方法。你不能调用clearCaches(),因为它是私有的。如果他们让它受到保护,但后来意识到它会导致性能问题,并且想要一个不再清除缓存的新实现,那么它们可能会破坏你仍然会调用它的覆盖实现。



所以基本上它是这样的,它们可以很容易地改变类中隐藏的部分,这些部分非常复杂,并且可以保护你免受破坏的子类(或者一个容易被破坏的类)。 / p>

I use the Scanner class for reading multiple similar files. I would like to extend it to make sure they all use the same delimiter and I can also add methods like skipUntilYouFind(String thisHere) that all valid for them all.

I can make a utility-class that contain them, or embed the Scanner Class as a variable inside another class but this is more cumbersome.

I have found some reasons to declare a class final, but why is it done here?

解决方案

Probably because extending it and overwriting some of it's methods would probably break it. And making it easier to overwrite methods would expose to much of the inner workings, so if in the future they decide to change those (for performance or some other reasons), it would be harder for them to change the class without breaking all the classes that extend it.

For example, consider the following method in the class:

public boolean nextBoolean()  {
    clearCaches();
    return Boolean.parseBoolean(next(boolPattern()));
}

Say you want to overwrite this because you want to make 'awesome' evaluate to a 'true' boolean (for whatever reason). If you overwrite it, you can't call super.nextBoolean(), since that would consume the next token using the default logic. But if you don't call super.nextBoolean(), clearCaches() won't be called, possibly breaking the other not overwritten methods. You can't call clearCaches() because it's private. If they made it protected, but then realized that it's causing a performance problem, and wanted a new implementation that doesn't clear caches anymore, then they might break your overwritten implementation which would still be calling that.

So basically it's so they can easily change the hidden parts inside the class, which are quite complex, and protecting you from making a broken child class (or a class that could be easily be broken).

这篇关于为什么java.util.Scanner类声明为'final'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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