+92 332 4229 857 99ProjectIdeas@Gmail.com

Polymorphism (C#.net)


Polymorphism  :
Polymorphic” literally means “of multiple shapes” and in the context of OOP, polymorphic means “having multiple behavior.
A polymorphic method results in different actions depending on the object are referenced, also known as late binding or run-time binding.

Code


public class Employee
{
     private int id;

     // Getter/Setter of id
     public int Id
     {
          get { return id; }
          set { id = value; }
     }

     private string name;

     // Getter/Setter of 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;
     }

     // defining display() function as virtual so that in derived class we can override it
     public virtual 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;
    }

   // overriding the base class display() function with the same name
    public override void display()
    {
         base.display(); // Call to base class display() method
         Console.Write(", And Degree : " + this.degree);
    }
}

public static void Main(string[] args)
{

      //Creating Employee Class Object References

      Employee employee1, employee2;

      employee1 = new Employee(10,"Osama");

      employee1.display(); // Call to base class display() function

      //Employee object can hold Teacher class because it is a derived class

      employee2 = new Teacher(12,"Saad","Bcs");

      employee2.display(); // Call to derived class display() function

      //But if you hold the Employee object to Teacher object it would give you ClassCastException
      
      Teacher teacher;
      teacher = (Teacher)new Employee(34, "Maryam");//Casting Employee To Teacher
      teacher.display();

}

0 comments: