Is it mandatory utility class should be final and private constructor?

后端 未结 4 555
逝去的感伤
逝去的感伤 2021-02-02 00:55

By making private constructor, we can avoid instantiating class from anywhere outside. and by making class final, no other class can extend it. Why is it necessary for Util clas

4条回答
  •  清歌不尽
    2021-02-02 01:31

    There is an important distinction between the Java Language, and the Java Runtime.

    When the java class is compiled to bytecode, there is no concept of access restriction, public, package, protected, private are equivalent. It is always possible via reflection or bytecode manipulation to invoke the private constructor, so the jvm cannot rely on that ability.

    final on the other hand, is something that persists through to the bytecode, and the guarantees it provides can be used by javac to generate more efficient bytecode, and by the jvm to generate more efficient machine instructions.

    Most of the optimisations this enabled are no longer relevant, as the jvm now applies the same optimisations to all classes that are monomorphic at runtime—and these were always the most important.

提交回复
热议问题