C# Single level inheritance sample

Program

using System;

namespace AboutClasses
{
    class SingleLevelInheritanceExample
    {
        //Example Single Level Inheritance
        class Person
        {
            protected string name;
            protected int age;
            protected int heightInCms;
            public void GetBasicDetails(string name, int age, int hgt)
            {
                this.name = name;
                this.age = age;
                this.heightInCms = hgt;
            }
            public void disBasicDetails()
            {
                Console.WriteLine("Name  : {0}", name);
                Console.WriteLine("Age   : {0}", age);
                Console.WriteLine("Height: {0} cms", heightInCms);
            }
        }
        // Derived class
        class Employee : Person
        {
            string Designation;
            int salary;
            public void GetEmploymentDetails(string desig, int salary)
            {
                this.Designation = desig;
                this.salary = salary;
            }
            public void disEmploymentDetails()
            {
                Console.WriteLine("Designation  : {0}", Designation);
                Console.WriteLine("Salary       : {0} OMR", salary);
            }
        }
        static void Main(string[] args)
        {
            Menu:
            Console.WriteLine("1.Unemployed\n2.Employed
                                                \nEnter your  choice");
            int choice = int.Parse(Console.ReadLine());
            switch (choice)
            {
                case 1:
                    Person p = new Person();
                    p.GetBasicDetails("Akbar", 20, 170);
                    p.disBasicDetails();
                    break;
                case 2:
                    Employee e = new Employee();
                    e.GetBasicDetails("Sultan", 30, 168);
                    e.GetEmploymentDetails("Defence", 1000);
                    e.disBasicDetails();
                    e.disEmploymentDetails();
                    break;
                default:
                    Console.WriteLine("Invalid choice");
                    Console.ReadKey();
                    goto Menu;
            }
            Console.ReadKey();

        }//main

    }//class

}//name-space


Note: 

The above program uses hard-coded data to produce output. If you wish you can convert the program to accept run-time inputs to generate output.

Output 1

1.Unemployed
2.Employed
Enter your choice
1
Name  : Akbar
Age   : 20

Height: 170 cms

Output 2

1.Unemployed
2.Employed
Enter your choice
2
Name  : Sultan
Age   : 30
Height: 168 cms
Designation  : Defence

Salary       : 1000 OMR


No comments:

Post a Comment