Private fields and encapsulation

I’m reading the head first c# book and don’t quite understand what this means.
“Any class can see private fields in another instances of the same class”

Consider these classes:

class A
{
    private int foo;

    public A(int f) { this.foo = f; }

    // works
    public int AddTo(A other) { return this.foo + other.foo; }

    // doesn't work: 'B.bar' is inaccessible due to its protection level
    public int AddTo(B other) { return this.foo + other.bar; }
}    

class B
{
    public B(int b) { this.bar = b; }

    private int bar;
}

var a1 = new A(123);
var a2 = new A(456);

var result = a1.AddTo(a2);

Here, the a1 instance of A accesses a2‘s private foo value. result will be 579.

However, the second method, AddTo(B) doesn’t work — it won’t even compile — because A instances don’t have access to B instances private members.

var b = new B(789);
var result2 = a1.Add2(b);

Here, a1 tries to access b‘s private bar member, but because a1 is an instance of A and b is an instance of B, the latter’s private bar member is inaccessible.

4

If class Foo has a private member, such as

public class Foo
{
    private int _bar;
}

Then _bar is accessible from within any instance of Foo.

public class Foo
{
    private int _bar;

    public bool MatchesOtherFoo(Foo other)
    {
        return _bar == other._bar;
    }
}

You couldn’t access _bar from another class, but you can access it from other instances of the same class.

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *