Rhexis
Rhexis

Reputation: 2542

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()
    {
        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??

Upvotes: 3

Views: 11092

Answers (4)

Dalton
Dalton

Reputation: 181

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.

Upvotes: 0

Noldorin
Noldorin

Reputation: 147260

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.

Upvotes: 5

Gian Paolo
Gian Paolo

Reputation: 514

Because Employee is an inner class of Person.

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

Upvotes: 0

SLaks
SLaks

Reputation: 887285

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.

Upvotes: 11

Related Questions