Access rules for protected members

Source: Internet
Author: User

A friend of mine asked me a few days ago, why cannot I access the protected method of the parent class in the subclass?

The Code she saw in a book is roughly as follows:

 

Public Class

{

Public string name = "";

Protected int age = 0;

}

Public class AB:

{

Public void Init ()

{

A A = new ();

A. Name = "lifengguo ";

A. Age = 24;

}

}

 

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

 

Protected is a protected member that can be accessed in its class and can be accessed by a derived class.

The above sentence contains three meanings:

1. The class itself can be accessed;

2. You can access the derived class;

3. the instance of the class cannot access the protected member.

 

The following code uses the protected member in the class itself.

Public Class

{

Public string name = "";

Protected int age = 0;

Public ()

{

Name = "lifengguo ";

Age = 24;

}

}

 

The following code uses the protected member in the derived class

Public class AB:

{

Public AB ()

{

Base. Name = "Li fengguo ";

Base. Age = 24;

}

}

 

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

Public Class C

{

Public void Init ()

{

A A = new ();

AB AB = 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.