+92 332 4229 857 99ProjectIdeas@Gmail.com

Inheritance (C#.net)


Inheritance In Classes:
Inheritance is a mechanism that allows you to extend a class with another class. Inheritance “is a” relationship i.e., teacher is a employee see below code example of inheritance. Create a new class as an extension of another class to make it more powerful. That is, the derived class inherits the public methods and public data of the base class.


Code

public class Employee
        {
       private int id;

       public int Id
       {
           get { return id; }
           set { id = value; }
       }

       private string name;

       public string Name
       {
           get { return name; }
           set { name = value; }
       }

       // Default Constructor
       public Employee()
       {
            this.id = 0;
            this.name = "Anonymous";
       }

      // Parameterized Constructor
       public Employee(int i, string n)
       {
            this.id = i;
            this.name = n;
       }

       public void display()
       {
          Console.WriteLine("Employee id:" + this.id + " name:" + this.name);
       }
}

public class Teacher : Employee // Inheriting Teacher from Employee
{
       private string degree;

       public string Degree
       {
          get { return degree; }
          set { degree = value; }
       }

     // Default Constructor
    public Teacher()
    {
        this.degree = "Fake One";
    }

    // Parameterized Constructor, passing id and name to Base class constructor
    public Teacher(int id, string name, string deg) : base(id, name)
    {
        this.degree = deg;
    }

    public void displayDeg()
    {
        base.display(); // Call to base class display() method
        Console.Write(", And Degree : " + this.degree);
    }
}

public static void Main(string[] args)
{

    Console.WriteLine("Making Object Of Emplyee Class");
           
    Employee employee = new Employee(10, "Rehan Ali"); 
       
    employee.display(); //call to Employee class display() method

    Console.WriteLine("Making Object Of Teacher Class");
            
    Teacher teacher = new Teacher (12, "Ali Haider", "Mcs");
         
    teacher.displayDeg(); //call to Teacher class displayDeg method

}



Output:


 Making Object Of Employee Class
   Employee Id: 10 : name: Rehan Ali
 Making Object Of Teacher Class
   Employee Id: 12 : name:Ali Haider , And Degree : Mcs

0 comments: