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
}
}