Why is the System class declared final and with a private constructor?

According to my understanding

Final class

The last class is just a class that cannot be extended.

A class with a single constructor without arguments

A class with private constructors cannot be created, except for the form inside the same class. This makes it useless for propagation from another class. But this does not mean that it cannot be subclassed at all, among inner classes we can expand and call a private constructor.

So, I understand that if we create a class with a single constructor without arguments, it makes no sense to declare this class final. Then why is the System class in Java declared as the final class, although it does not have a single constructor with no arguments?

I heard that creating a class finale has some increase in performance . Is this correct and is this the only reason to declare the System class final? Please clarify why Java implemented the System class as follows.

+6
source share
1 answer

Sometimes you need some β€œutility” classes that contain some static utilities. These classes are not expected to be extended. Thus, developers can make some defensive decisions and mark such classes as "final". I would say that marking a Java class with "final" can lead to minor performance improvements in Hotspot (see https://wikis.oracle.com/display/HotSpotInternals/VirtualCalls ). But, I am sure that it was a design decision, not performance.

You can use final classes if you want to have some objects of immutable value, and also if you want classes to be created only through their factory methods. Objects of immutable value are especially useful when working 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 of these construction details behind the factory method. Moreover, you can control through the factory the number of instances of this class at runtime - as in single games.

As I said, all these are design decisions. I am sure that there are no remarkable performance gains caused by the final classes.

+3
source

Source: https://habr.com/ru/post/987270/


All Articles