开发者

Accessing Private variables in a child class?

So i was browsing some code and i came across:

public class Person
{
    private string message;

    public override string ToString开发者_如何学C()
    {
        return message;
    }

    public static Person CreateEmployee()
    {
        return new Employee();
    }

    class Employee : Person
    {
        public Employee()
        {
            this.message = "I inherit private members!";
        }
    }
}

Can someone please explain how the private variable "message" is being used/accessed even though its private??


Private members are accessible to all code within the class, including nested classes.
If you move the Employee class outside the Person class, it will fail until you make the field protected.


The simple fact is, this works because compilers allow it to - the designers thought it was a good thing. Once code is compiled, private/public variables are stored in memory in exactly the same way. (The CLR is simply aware of different metadata attributes for them.)

The justification is: nested classes and their members are still considered to lie conceptually/hierarchically within the parent class. Hence, private members of the parent class are always accessible by these semantics. Besides, it just makes life easy for programmers in many cases without breaking the object-oriented encapsulation rule!

In fact, if you want to think about this in terms of code, any code that falls within the open and close braces of a given class can access its private members, regardless of whether it immediately lies within a nested class/struct/etc.


Because Employee is an inner class of Person.

See this question: can-inner-classes-access-private-variables


Person={private message, private Employee}

Private Employee and private message are siblings, Employee can use the message. If you allocate Private Message into another class and mark it as protected/private outside the Person class, then Employee will not be able to see or use it anymore even with an instance of that class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜