Method overriding



Method Overriding


    public class Person
    {
        public virtual void isOnPayroll()
        {
        // Logic to Check is the person is on payroll or not.
            Console.WriteLine("In Person Class");
        }
    }
    public class Employee : Person
    {
        public override void isOnPayroll()
        {
            // The method is overriden in the child class.
            // The Employee class can override the isOnPayroll or it can make it virtual for further derived class.
            Console.WriteLine("In Employee Class");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Person person1 = new Person();
            person1.isOnPayroll(); // In Person Class because the object is of person.
            Employee emp = new Employee();
            emp.isOnPayroll();      // In Employee Class overridden method is called.
            Person refobj = new Employee();
            refobj.isOnPayroll();  // In Employee Class. Reference of person class is used and object of Employee
                                    // is created.
            Console.Read();
        }
    }



Method Hiding

        public class Person
        {
            public virtual void isOnPayroll()
            {
            // Logic to Check is the person is on payroll or not.
                Console.WriteLine("In Person Class");
            }
        }
        public class Employee : Person
        {
            public new void isOnPayroll()
            {
                // The method is overriden in the child class.
                // The Employee class can override the isOnPayroll or it can make it virtual for further derived class.
                Console.WriteLine("In Employee Class");
            }
        }

        class Program
        {
            static void Main(string[] args)
            {
                Person person1 = new Person();
                person1.isOnPayroll(); // In Person Class because the object is of person.
                Employee emp = new Employee();
                emp.isOnPayroll();      // In Employee Class overridden method is called.
                Person refobj = new Employee();
                refobj.isOnPayroll();  // In Person Class. Reference of person class is used and object of Employee
                                        // is created. Information Hiding is done here
                Console.Read();
            }
        }








No comments:

Post a Comment