Why do you need a protected constructor in java?

  • Maybe for the implementation of the base class singleton? - DanielOlivo

2 answers 2

protected constructor allows you to disable the creation of an instance of the base class. In derived classes, this constructor will be available, and therefore it will be possible to create descendants.

This approach is applicable in many OOP languages, not only in .

  • As far as I understand, it does not quite allow you to prohibit the creation of an instance of the base class , but to create an instance of the base class directly by this constructor. A class may well have a static function inside which this protected constructor would be called, or call this constructor from another public constructor - Grundy
  • And how does this approach differ from class declaration abstract? - Max Art
  • one
    @MaxArt, because an instance of the class can still be created, an instance of an abstract class — it is impossible - Grundy
  • It would be cool to see in the answer a couple of examples of how this can be applied) - YuriySPb
  • And an instance of a class with a protected constructor can still be created in the classes of the same package? - Max Art

A protected constructor is needed to call it from the heirs, but hiding from outside access.
A great example is the protected constructor for the Throwable class.

 Throwable(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) 

The last parameter indicates whether it is necessary to write a template frame (which is a very expensive operation). You can inherit from Throwable and, by calling this parent constructor, get very lightweight "signal" exceptions.

  • It seems to me, or in the first sentence the words are missing, not only after "needed" and for after "but"? - Grundy
  • I'm still inclined to think that you think. Offer takes a slightly different color. - Nikolay Romanov
  • yes, the heavy phrase came out :) - Grundy