Start-up, protected is no longer protected

Source: Internet
Author: User

Today, I read Delphi's e-book and found that in Delphi, I accessed its parent class in a "spoofing" way that violates access permission rules. At this point, I think of a problem, that is, when protected encapsulates and protects objects, there are obvious backdoors. In C #, we can easily expose protected to public. For example:

 

Class Base
{
Protected   Void Print ()
{
Console. Write ("This is protected method in base class!");
}
}

Class Derived: Base
{
Public   New   Void Print ()
{
Base. Print ();
}
}

With this method, we can access the print () method of the base without scruples in another class.

Class Otherclass
{

[Stathread]
Static   Void Main ( String [] ARGs)
{
Derived d= NewDerived ();
D. Print ();
Console. Readline ();
}
}

In other words, if we want to expose the protected method or field of a class, OK, we only need to generate a Wrapper class (for the user, it is like packing the class, in essence, it uses an inherited method) to derive this class, and then define the new protected method as public. Such a "spoofing" method can easily steal the class's protected methods.

That is to say, through the inheritance method, we can improve the access level set by the parent class. Of course, the private of the parent class is powerless.

Therefore, should Derived classes directly derive their protected methods? We should choose a new one based on the actual situation.

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.