Polymorphism examples



Polymorphism is an object-oriented programming concept that refers to the ability of a variable, function or object to take on multiple forms. In a programming language exhibiting polymorphism, class objects belonging to the same hierarchical tree (inherited from a common parent class) may have functions with the same name, but with different behaviors.



Example

The classic example is of the Shape class and all the classes that are inherited from it, such as:


Rectangle


Triangle


Circle

This Code is written in C++

class Shape
{
  public:
  Shape(){}
  //defining a virtual function called Draw for shape class
  virtual void Draw(){cout<<"Drawing a Shape"<<endl;}
};

class Rectangle: public Shape
{
  public:
  Rectangle(){}
  //Draw function defined for Rectangle class
  virtual void Draw(){cout<<"Drawing a Rectangle"<<endl;}
};

class Triangle: public Shape
{
  public:
  Triangle(){}
  //Draw function defined for Triangle class
  virtual void Draw(){cout<<"Drawing a Triangle"<<endl;}
};

class Circle: public Shape
{
  public:
  Circle(){}
  //Draw function defined for Circle class
  virtual void Draw(){cout<<"Drawing a Circle"<<endl;}
};


int main() {
 
  Shape *s;
 
  Triangle tri;
  Rectangle rec;
  Circle circ;
 
  // store the address of Rectangle
  s = &rec;
  // call Rectangle Draw function
  s->Draw();
 
  // store the address of Triangle
  s = &tri;
  // call Traingle Draw function
  s->Draw();
 
  // store the address of Circle
  s = &circ;
  // call Circle Draw function
  s->Draw();
 
  return 0;
 
}



This code is written in python.

# def add(x,y,z=0):
# return x+y+z
#
# print(add(2,0))
# print(add(2,3,5))

#
# todo Polymorphism using class
# class india:
# def capital(self):
# print("Delhi is capital of India")
# def Language(self):
# print("Hindi is offical lanaguage of India")
# class Usa:
# def capital(self):
# print("Washington is capital of India")
# def Language(self):
# print("English is offical lanaguage of USA")
#
# obj_ind=india()
# obj_usa=Usa()
#
# for c in (obj_ind,obj_usa):
# c.capital()
# c.Language()
# todo: Polymorphism Using inheritance

# class Bird:
# def Intro(self):
# print("There are many time birds in World")
#
# def flight(self):
# print("Every birds can fly but some not")
#
# class sparrow(Bird):
# def Flight(self):
# print("Sparrow can fly")
#
# class ostrich(Bird):
# def Flight(self):
# print("ostrich can not fly ")
#
#
# obj_bird=Bird()
# obj_sp=sparrow()
# obj_os=ostrich()
#
#
# obj_bird.Intro()
# obj_bird.flight()
#
# obj_sp.Intro()
# obj_sp.Flight()
#
# obj_os.Intro()
# obj_os.Flight()









 

Comments

Popular posts from this blog

React Installation with Vite and Tailwind css (Steps to Installation)

Insert Data In mongoDb

Class methods as an alternative Constructor