Today, I found that the class of a private constructor cannot be instantiated externally or inherited.
This is because the subclass executes the constructor of the subclass before executing the constructor of the base class. However, if the base class constructor is private, it cannot be accessed. Therefore, an error occurs during compilation.
For example:
Public class baseclass
{
Private baseclass ()
{
}
}
Public class newclass: baseclass
{
Public newclass ()
{
}
}
During Compilation: Error 1 "baseclass. baseclass ()" is not accessible because it is restricted by the protection level
Which of the following constructor functions is used? In fact, during subclass construction, unless you display that you call a constructor of the base class, only the default constructor in the base class will be executed, that is, the one without any parameters.
For exampleCodeThe compilation is successful.
Public class baseclass
{
Public baseclass ()
{
}
Baseclass (int I)
{
}
}
Public class newclass: baseclass
{
Public newclass ()
{
}
Public newclass (int I)
{
}
}
That is to say, as long as the default constructor of the base class is not private, it can be inherited. However, if you explicitly call a private constructor of the base class in the subclass, the compilation will still fail (the error is the same as above ).
For example:
Public class baseclass
{
Public baseclass ()
{
}
Baseclass (int I)
{
}
}
Public class newclass: baseclass
{
Public newclass ()
{
}
Public newclass (int I): Base (I)
{
}
}
In the code above, the second constructor of newclass explicitly calls a private constructor of the base class, and fails...
Of course, private constructor is rarely used (it is used in the single-piece mode and can only construct instances within the class ).