About the access permissions of protected members

Source: Internet
Author: User

A friend of mine asked me a few days ago why the parent class cannot be accessed in the subclass.ProtectedMethod?

What she saw in a bookCodeProbably as follows:

 

Public Class A

{

Public StringName ="";

Protected IntAge = 0;

}

Public Class AB:A

{

Public VoidInit ()

{

AA =New A();

A. Name ="Lifengguo";

A. Age = 24;

}

}

 

But she is always unable to pass during compilation. She asked me why? My understanding is:

 

ProtectedIs a protected member, which can be accessed in its class and can be accessed by a derived class.

The above sentence contains three meanings:

1,Class itself can be accessed;

2,Can be accessed in the derived class;

3,Class instances are inaccessible.ProtectedMember.

 

The following code is used in the class itselfProtectedMember

Public Class A

{

Public StringName ="";

Protected IntAge = 0;

PublicA ()

{

Name ="Lifengguo";

Age = 24;

}

}

 

The following code is used in the derived classProtectedMember

Public Class AB:A

{

PublicAB ()

{

Base. Name ="Li fengguo";

Base. Age = 24;

}

}

 

The following code is a member of the Instance category class:

Public Class C

{

Public VoidInit ()

{

AA =New A();

ABAB =New AB();

A. Name ="Lifengguo";// OK

AB. Name ="Li fengguo";// OK

A. Age = 24;// Error

AB. Age = 24;// Error

}

}

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.