#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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: