Friday, April 23, 2021

C# Access Specifier - protected

using System;

namespace Console_AccessSpecifierProtected
{
    class Student
    {
        protected int age = 20;
        protected void ShowAge()
        {
            Console.WriteLine("Protected age accessible inside its own class, age: {0}", age);
        }
    }

    class ScienceStudent : Student
    {
        public void ShowProtectedAge()
        {
            // derive class can access protected method of parent class
            this.ShowAge(); 
            Console.WriteLine("Protected age accessed by derived class method: {0}", age);
            int AgeChanged = age + 10;
            Console.WriteLine("Changed age:{0}", AgeChanged);
            
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            /*Program class is not derived class of Student class.
             * So, it cannot access protected member of Student class.
             * For example, Intellisense will not show age.
             */
            ScienceStudent ss = new ScienceStudent();
            ss.ShowProtectedAge();
            /* Parent class reference variable can refer to its derived class objects. */
            Student student = new ScienceStudent();
            Console.WriteLine(student.GetHashCode());
            /* But all members of student are protected
             * so, student object cannot access them in Program class
             * But the derived class objects can access the members of the Parent class.
             * So, we can create a derive class and access Parent class members through child class object.
             */

            Console.Read();
        }
    }
}

OUTPUT
Protected age accessible inside its own class, age: 20
Protected age accessed by derived class method: 20
Changed age:30
58225482

No comments:

Post a Comment

Hot Topics