我正在读一本关于Java的书,它说你可以将整个类声明为final。我想不出有什么地方可以用它。

我只是一个编程新手,我想知道程序员是否真的在他们的程序中使用这个。如果他们使用,他们什么时候使用,这样我就能更好地理解它,知道什么时候使用它。

如果Java是面向对象的,并且你声明了一个final类,难道它不会阻止类具有对象的特征吗?


当前回答

Final类不能扩展。因此,如果你想要一个类以某种方式运行,并且不希望有人重写方法(可能效率较低,恶意代码更多),你可以将整个类声明为final或你不想被更改的特定方法。

由于声明一个类并不会阻止一个类被实例化,这并不意味着它会阻止类具有对象的特征。只是您必须坚持使用类中声明方法的方式。

其他回答

Final类不能进一步扩展。如果不需要在java中使类可继承,可以使用这种方法。

如果我们只需要让一个类中的特定方法不被覆盖,我们可以把final关键字放在它们前面。在那里类仍然是可继承的。

final类可以避免在添加新方法时破坏公共API

假设在基类的版本1中:

public class Base {}

客户会这样做:

class Derived extends Base {
    public int method() { return 1; }
}

然后,如果在版本2中,你想添加一个方法method到Base:

class Base {
    public String method() { return null; }
}

这将破坏客户端代码。

如果我们使用final类Base,客户端就不能继承,方法的添加也不会破坏API。

Be careful when you make a class "final". Because if you want to write an unit test for a final class, you cannot subclass this final class in order to use the dependency-breaking technique "Subclass and Override Method" described in Michael C. Feathers' book "Working Effectively with Legacy Code". In this book, Feathers said, "Seriously, it is easy to believe that sealed and final are a wrong-headed mistake, that they should never have been added to programming languages. But the real fault lies with us. When we depend directly on libraries that are out of our control, we are just asking for trouble."

相关阅读:Bob Martin的《开闭原理》。

主要引用:

软件实体(类、模块、 函数等)应该是开放的 分机,但已关闭 修改。

最后一个关键字是在Java中强制执行的方法,无论是在方法上还是在类上。

Final类不能扩展。因此,如果你想要一个类以某种方式运行,并且不希望有人重写方法(可能效率较低,恶意代码更多),你可以将整个类声明为final或你不想被更改的特定方法。

由于声明一个类并不会阻止一个类被实例化,这并不意味着它会阻止类具有对象的特征。只是您必须坚持使用类中声明方法的方式。