protected Access Specifier

The protected access specifier allows class members to be accessed  only by those who inherits from them. We learned about the public and private access specifiers. The protected access specifier is used when only the derived classes and the class itself should be able to access the members. Other classes that do not inherit from the class with a protected member will be denied access. The table below shows the accessibility of the three access specifiers.

Accessible from public private protected
Inside the class true true true
Outside the class true false false
Derived class true false true

Figure 1 – Accessibility of Access Specifiers

You can see that public is the most accessible. Regardless of location, public members and methods can be called or accessed. The private is only accessible inside the class where it belongs. The protected access specifier is accessible inside the class where it is defined and also the derived classes of its class. protected members are prohibited from classes that have no relation. The          example code below further shows you their behavior.

using System;
 
namespace ProtectedAccessSpecifierDemo
{
    class Parent
    {
        protected int protectedMember = 10;
        private int privateMember = 10;
        public int publicMember = 10;
    }
 
    class Child : Parent
    {
        public Child()
        {
            protectedMember = 100;
            privateMember = 100; // ERROR
            publicMember = 100;
        }
    }
 
    class Program
    {
        public static void Main()
        {
            Parent myParent = new Parent();
 
            myParent.protectedMember = 100; // ERROR
            myParent.privateMember = 100; // ERROR
            myParent.publicMember = 100;
        }
    }
}

Example 1 – Access Specifiers Demo

Lines 17,28, and 29 will produce an error because they are not allowed to access the protected fields of the Parent class.  As you can see in line 17, the Child class is  trying to access the private member of Parent.  Since private members are inaccessible from the outside, event from derived  classes, line 17 will produce an error. If you will notice line 16, the Child class accesses the protected member of the Parent class and it was successful because the Child class is a derived class of the Parent. But if you will look at line 28 where the Program class access the protected member of the Parent  class, it produces an error since the Program  class does not inherit from the Parent class.  Likewise, the Program class cannot also access the  private member of the Parent class.

Written by compitionpoint

Leave a Comment

Your email address will not be published. Required fields are marked *