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

梦想与她 提交于 2019-12-07 03:43:39

问题


As per my understanding

Final class

A final class is simply a class that can't be extended.

A class with single no argument private constructor

A class with private constructors cannot be instantiated except form inside that same class. This make it useless to extend it from another class. But it does not mean it cannot be sub classed at all, among inner classes we can extend and call the private constructor.

So my understanding is, if we create a class with single no argument private constructor, their is no meaning to declare that class as final. Then why System class in Java, declared as final class although it has single no argument private constructor?

I heard that making a class final has some performance gain. Is this correct and is this the only reason to declare the System class as final? Please clarify me why Java implemented the System class like this.


回答1:


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.



来源:https://stackoverflow.com/questions/30258274/why-system-class-declared-as-final-and-with-private-constructor

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