The article presents the author's understanding of the chapter from the book
Effective Java, Second Edition by Joshua BlochIn simple language, we define the concept of an abstract and final class:
An abstract class cannot be instantiated, but it can have subclasses.
The final class is the class from which it is forbidden to inherit.
For a more precise definition, refer to the official tutorial:
The combination of abstract and final for a class means that a class cannot have heirs and it is not possible to create an instance for this class.
')
We need to make the class abstract and final at the same time, for example, when we go to create a class of utilities consisting of static methods (for example java.lang.Math or java.util.Arrays).
Decision
public class UtilityClass {
private UtilityClass() {
throw new AssertionError();
}
... //
}
* This source code was highlighted with Source Code Highlighter .
As you know, the default constructor is created only if the class does not contain any explicit constructors. Therefore, by defining a private constructor with no parameters for the class, we will provide a ban on instantiating it from code outside the class. AssertionError is not strictly required, but it provides insurance in case a constructor is accidentally called from a class. This ensures that the class will not be instantiated under any circumstances (abstract). This idiom also prevents the creation of subclasses from this class (final). All constructors must call the superclass constructor explicitly or implicitly, and subclasses of this class will not have access to the constructor of the base class.