Can a class of a private constructor be a subclass?

Source: Internet
Author: User
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 ).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.