java - Why System class declared as final and with private constructor? -
this question has answer here:
as per understanding
final class
a final class class can't extended.
a class single no argument private constructor
a class private constructors cannot instantiated except form inside same class. make useless extend class. not mean cannot sub classed @ all, among inner classes can extend , call private constructor.
so understanding is, if create class single no argument private constructor, no meaning declare class final. why system class in java, declared final class although has single no argument private constructor?
i heard making class final has performance gain. correct , reason declare system class final? please clarify me why java implemented system class this.
sometimes, need "utility" classes, contain static utility methods. classes not expected extended. thus, developers may make defensive decisions , mark such classes "final". say, marking java class "final" may cause tiny little performance improvements in hotspot (please refer https://wikis.oracle.com/display/hotspotinternals/virtualcalls). but, pretty sure, design decision rather performance.
you can use final classes, if want have immutable value objects well, or if want make classes instantiated through factory methods. immutable value objects useful while dealing 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 static factory method, can hide construction details, behind factory method. moreover, can control, through factory, number of instances of class in runtime - in singletons.
as told, these design decisions. pretty sure there no remarkable performance gain brought final classes.
Comments
Post a Comment