#751 – Inheritance Only Partially Preserves Encapsulation

It can be argued that inheritance breaks encapsulation, since there is a tight coupling between the parent and child classes and because the child class can override behavior in the parent class.

But inheritance does partially preserve encapsulation, with respect to private members of the base class.

  • An instance of the child class can’t access private members in the base class
  • The implementation of the child class can’t access private members in the base class

Assume that we have a Dog class with a private field barkCount and a Terrier class that derives from Dog.

            Terrier t = new Terrier();

            // ERROR: Dog.barkCount inaccessible due to its protection level
            int i = t.barkCount;

Also:

    public class Terrier : Dog
    {
        public void Test()
        {
            Console.WriteLine("Terrier " + Name);

            // ERROR: Dog.barkCount inaccessible due to its protection level
            int i = this.barkCount;
        }
    }
Advertisements