Why System class declared as final and with private constructor? [duplicate]

ⅰ亾dé卋堺 提交于 2019-12-05 07:19:28

Sometimes, you need some "utility" classes, which contain some static utility methods. Those classes are not expected to be extended. Thus, developers may make some defensive decisions and mark such classes "final". I would say, marking a Java class with "final" may cause a tiny little performance improvements in Hotspot (please refer to https://wikis.oracle.com/display/HotSpotInternals/VirtualCalls). But, I am pretty sure, that it was a design decision rather than performance.

You can use final classes, if you want to have some immutable value objects as well, or if you want to make the classes be instantiated only through their factory methods. Immutable value objects are especially very useful while dealing with concurrency:

public final class MyValueObject {
   private final int value;
   private MyValueObject(int value) { this.value = value; }
   public static MyValueObject of(int value) { return new MyValueObject(value); }  
}

Using the static factory method, you can hide all those construction details, behind the factory method. Moreover, you can control, through that factory, the number of instances of that class in runtime - as in singletons.

As I told, all these are design decisions. I am pretty sure that there is no remarkable performance gain brought by final classes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!