Method overloading and overriding in Python

 Overriding:

  • Method overriding is a mechanism in which a subclass inherits the methods of the superclass and sometimes the subclass modifies the implementation of a method defined in the superclass.
  • That means if subclass (Derived class) has the same method as declared in the parent class (base class).
  • Method overriding is used for runtime polymorphism.

Rules for Java Method Overriding:

  • The method must have the same name as in the parent class
  • The method must have the same parameter as in the parent class.
  • There must be inherited.
  • A static method cannot be overridden. It can be proved by runtime polymorphism.

Syntax:

  1. class base_class_name:

    def method_name(parameter_list):

              //Statement

     

    class derived_class_name(base_class_name):

    base_class_method(parameter_list):

              //Statement

Example program:

  1. #method overriding or runtime polymorphism

    class Shape:

        result=0

        def area(self):

            print("\n\tCalculating area of Rectangle,Circle,Triangle .........")

    class Rectangle(Shape):

        def area(self):

            l=int(input("Enter length: "))

            w=int(input("Enter width: "))

            result=l*w; #area=length*width;

            print("Area of rectangle : ",result)

           

    class Circle(Shape):

        def area(self):

            r=float(input("Enter radius  of circle : "))

            result=3.14*r*r; #area=3.14*radius*radius;

            print("Area of circle : ",result)

     

    s=Shape()

    s.area()

    r=Rectangle()

    r.area()

    c=Circle()

    c.area()

Output:

Method overloading:

  • Overloading is a mechanism in which we can use many methods having the same function name but can pass the different numbers of parameters or different types of parameters.
  • In python, doest not call the data types at function definition.
  • So python does not support method overloading.
Share:

No comments:

Post a Comment

Recent Posts

Service Support

Need our help to Learn or Post New Concepts Contact me