upGrad KnowledgeHut SkillFest Sale!-mobile

HomeBlogProgrammingWhat is Polymorphism in OOPs

What is Polymorphism in OOPs

Published
26th Apr, 2024
Views
view count loader
Read it in
14 Mins
In this article
    What is Polymorphism in OOPs

    Any data that may be processed in more than one form is said to be polymorphic. The word "morphism" already conveys its meaning because poly means "many" and morphism "types." Polymorphism is one of the most crucial concepts in an object-oriented programming language. The most typical application of polymorphism in object-oriented programming (OOPs) is when an object from a child class is referenced using a parent class reference. Here, we'll look at how to represent any function using a variety of types and formats.

    A person can simultaneously play multiple roles in their life, which is an example of polymorphism in OOPs in real life. A mother, a wife, an employee, and a daughter are all roles that are like those of a woman. The same person must therefore possess various traits while implementing each according to the circumstance. One of the key components of object-oriented programming is polymorphism.

    The main strength of object-oriented programming is polymorphism. But why do we use polymorphism? Because languages that don't enable polymorphism cannot claim to be object-oriented languages because it is so crucial. Object-based languages are those that have classes but no polymorphism capability. For an object-oriented programming language, it is therefore essential.

    It is the capacity of an item or reference to assume several forms in various contexts. Function overloading, function overriding, and virtual functions are all implemented.

    Consider where the subclasses Horse, Fish, and Bird descend from a base class called Animals. Assume that all of the above subclasses inherit the Animals class's Move function. Each subclass may implement the function uniquely thanks to polymorphism.

    The Move function, for instance, may reply to a call by displaying trotting on the screen when it is invoked on a Horse class object. However, swimming could be seen on the screen when the same function is run on a Fish class object. It might be flying if the thing is a bird.

    What is Polymorphism in OOPs?

    Every object-oriented programming language must include the fundamental concept of polymorphism, which is inseparable from OOPs. An object or reference can have distinct forms in various contexts. Polymorphism would be defined as "a property of having numerous forms" since, as the name suggests, "poly" denotes "many," and "morph" refers to "forms."

    A single interface in the object-oriented programming language handles both classes and objects. It puts virtual functions, overriding, and function overloading into practice. Additionally, it is frequently employed in programming to instrument inheritance.

    One of the important OOPS ideas is polymorphism. You can have different or numerous kinds of objects and variables or use polymorphism methods. Polymorphism allows for different implementations of the same method depending on the requirements of the class.

    The polymorphism idea provides great scalability and improved readability. You can provide polymorphism so that each instance of the Parent class's method has a different implementation. In most cases, it is possible to access it through inheritance, which presupposes that the class must be a member of the same hierarchy tree. It is essential to understand how polymorphism is implemented in programming and how class objects can be used to access it.

    It indicates that a reference or item has the capacity to take on different forms at different times. Function overloading, function overriding, and virtual functions are all used.

    The polymorphism feature can send any message to objects of different classes. Every object has the propensity to react appropriately according to the class attributes.

    Example of Polymorphism in OOPs

    real-life example of polymorphism

    1. A person performs the roles of a worker at work, a father at home, and a shopper at malls.
    2. A security guard outside the organization behaves differently when different people enter. When the boss shows up, he behaves in one way, and when the employees show up, he behaves differently.
    3. A boy introduces his romantic relationship with the term "friendship," and the girl ends it with the same phrase. The girl promises that we will remain close friends forever.
    4. Assume that when you are in a classroom, you act like a student; when you are in a store, you act like a consumer; and when you are at home, you act like a son or daughter. One person is visible here, acting in various ways. Assume that when you are in a classroom, you act like a student, when you are in a store, you act like a consumer, and when you are at home, you act like a son or daughter, one person is visible here, acting in various ways.

    Why is Polymorphism Used?

    The idea of polymorphism enables you to carry out a single activity in a number of different ways. You can specify a single interface and take advantage of numerous implementations. The word "polymorphism" is used to describe polymorphism in such a way that "morphs" denotes forms and "poly" denotes many. So, it indicates a variety of shapes.

    1. One of the main advantages of polymorphism is that it enables the computer code to grow and utilize earlier programs. The developers' time and effort are therefore saved.
    2. The fundamental concepts of OOPs languages are also used to program many kinds of complex code execution.
    3. The polymorphism capability enables programming to write code more quickly and creatively.
    4. Coding legible software reduces coupling and increases reuse.
    5. The developer can reuse the software codes thanks to polymorphism. It implies that outdated codes and classes that have already been created, verified, and used can be reused when necessary. It helps programmers by saving time. These codes and their related classes may therefore be applied to other techniques.
    6. Float, Int, Long, Double, and other forms of data can all only be stored in a single variable. It makes it easier for consumers to look for and use the different kinds of variables they employ.

    KnowledgeHut has a fascinating course opportunity for beginners in Java Programming. It has workshops with hands-on learning and 40 hours of instructor-led online lectures.

    Types of Polymorphism in OOPs

    types of polymorphism

    Source

    There are two types of polymorphism in OOPs:

    1. Static 
    2. Dynamic 

    1. Static Polymorphism

    In object-oriented programming polymorphism languages, one can achieve static polymorphism by employing the overloading technique. The programmer would be able to use a variety of ways with this approach. Despite sharing names, they have different parameters. Overloading methods are an example of static polymorphism. Static polymorphism requires a few certain criteria to exist. As follows:

    • The kinds of each parameter would need to be distinct.
    • It's possible that the parameter's order needs to change.
    • One method would need to have a different set of parameters than the other method.

    The language's compiler would identify different methods during run time by locating their signatures.

    When a particular method call is made while the program is being compiled, the compiler will first determine the method signature and then choose the method. The Compile time execution time Although polymorphism is more efficient, this method is not very versatile. 

    The following is an example of polymorphism in OOPs where compile-time polymorphism can be seen: 

    // Java program to demonstrate 
    // compile-time polymorphism 
    public class GFG { 
        // First addition function 
        public static int add(int a, int b) 
        { 
            return a + b; 
        } 
        // Second addition function 
        public static double add( 
            double a, double b) 
        { 
            return a + b; 
        } 
      
        // Driver code 
        public static void main(String args[]) 
        { 
            // Here, the first addition 
            // function is called 
            System.out.println(add(2, 3)); 
      
            // Here, the second addition 
            // function is called 
            System.out.println(add(2.0, 3.0)); 
        } 
    } 

    Output: 

    5 
    5.0 

    2. Dynamic Polymorphism

    Another name for this procedure is runtime polymorphism. Under this procedure, a single call to an overridden method is resolved while the application is running. The best example of runtime polymorphism is method overriding, where the compiler does not handle the call.  

    Using pointers and virtual functions, overriding is accomplished. The act of declaring a single method in a subclass that is already existent in the parent class is known as method overriding. The kid class would acquire a method for implementation through this approach. The parent class of the child class provides this function. 

    Although this polymorphism process is slower than static polymorphism, it is more versatile. 

    Without altering or changing the codes of the parent class object, it is feasible to transfer one method's implementation to another. As a result, if one child class requires the parent class implementation method while another child class may use the overriding feature to have an alternative implementation method. 

    A single method is declared in a subclass that is part of the parent class in method overriding. The child class gets an implementation technique. 

    The class supplies its own specification to another inherited method during runtime polymorphism. This method transfer is accomplished without altering the object codes of the parent class. 

    The following is an example where runtime polymorphism can be seen: 

    // Java program to demonstrate 
    //runtime polymorphism// runtime polymorphism 
    // Implementing a class 
    class Test { 
        // Implementing a method 
        public void method() 
        { 
            System.out.println("Method 1"); 
        } 
    } 
      
    // Defining a child class 
    public class GFG extends Test { 
      
        // Overriding the parent method 
        public void method() 
        { 
            System.out.println("Method 2"); 
        } 
      
        // Driver code 
        public static void main(String args[]) 
        { 
            Test test = new GFG(); 
      
            test.method(); 
        } 
    } 

    Output: 

    Method 2 

    Important Concepts About Polymorphism in OOPS

    What are the principles of Polymorphism in OOPS? 

    OOP polymorphism refers to the biological concept that various stages or forms of a species or organism are possible. Object-oriented programming and languages like Java can both use this principle. 

    When two or more methods in a class have the same method name but different parameters, this is known as overloading in OOP polymorphism. When two methods use the same method name and parameters, it occurs. The two most widely used techniques for overloading and overriding polymorphism in parent and child classes are described here. 

    Which Type of Function Shows Polymorphism?

    Operator or function overloading is a method for obtaining compile-time polymorphism. When there are numerous functions with the same name, this is known as function overloading. These routines are referred regarded as being overloaded if numerous different parameters are used. 

    What is a Method in OOP?

    The polymorphism technique states that it is a programmed procedure that is defined as a component of a class and integrated into any object of the specific class. A class or an object may contain several methods. 

    KnowledgeHut has a fascinating course opportunity for beginners in a Python Programming course. It has hands-on learning with 24 hours of instructor-led online lectures. Apart from that, the course has 100 hours of MCQs and three live projects. 

    Difference Between Compile Time And Runtime Polymorphism

    1. Compile Time Polymorphism

    Compile-time polymorphism occurs whenever an object is associated with its functionality at the moment of compilation. By examining the method signatures, OOPs determine the method to call at compile time. Compile-time polymorphism, static polymorphism, or early binding are all terms for this. Method overloading is used to achieve compile-time polymorphism. According to method overloading, a class may contain many functions with the same name but different prototypes. One technique to create polymorphism is through function overloading. However, this depends on the technology used and the kind of polymorphism chosen. 

    2. Runtime Polymorphism

    Runtime polymorphism is the process of binding an object to functionality during runtime. Method overriding can be used to achieve runtime polymorphism. It is also known as late binding or dynamic binding. According to the concept of method overriding, the parent class's method is overridden in the child class. This indicates that method overriding occurs when a child class provides a specific implementation of a method that was given by one of its parent classes. 

    Comparison Table

    Compile Time PolymorphismRun time Polymorphism
    The compiler resolves the call in compile-time polymorphism.The compiler does not resolve the call in runtime polymorphism.
    Additionally known as overloading, early binding, and static binding.Overriding, late binding and dynamic binding are other names for it.
    Method overloading is a sort of compile-time polymorphism in which several methods with the same name but distinct parameters, signatures, or return types are combined.Method overriding is a type of runtime polymorphism when the same method with identical parameters or a similar signature is linked to a different class.
    Operator and function overloading are used to achieve it.Pointers and virtual functions are used to do it.
    Because the method that has to be executed is known early during compilation, it allows for quick execution.Because the method that needs to be executed is known at runtime, it offers slower execution than early binding.
    Given that everything is executed at compile time, compile time polymorphism is less flexible.The fact that everything is executed at the run time makes runtime polymorphism more versatile.

    Advantages of Using Polymorphism

    • It helps the programmer reprocess the source code. It entails that previously written codes and classes that have been verified and executed can be reused as needed, saving a programmer's time. Thus, these codes and associated classes may be applicable to several additional techniques. 
    • Only one variable can be used for storing several data types, such as Int, Float, Double, Long, etc.. It makes it simpler to look for and use these kinds of variables that users use. 
    • Simple code debugging. 
    • It aids in preserving and reducing the connectivity between different functionalities. 
    • Gives programmers the freedom to create programs that, depending on the situation, employ just one technique for numerous executions. 
    • One of its biggest benefits is that it enables programming code to grow and use the previous program, saving time and work for developers. 
    • The fundamental idea behind OOPs languages, this technique is also used to program many kinds of large-scale code execution. 
    • This polymorphism feature makes it possible for programmers to create codes more quickly and creatively. 
    • The benefits of polymorphism claim that it is fundamentally desirable since it minimizes coupling and maximizes reusability to create readable program code. Although polymorphism may occasionally cause a slight performance hit, this does not mean that it is always necessary. It facilitates code maintenance and makes later reading of the code simple. 

    Conclusion

    One of the fundamental ideas of OOP languages, polymorphism, explains the idea of using many classes with the same interface. Each of these classes is capable of offering a unique interface implementation. 

    A method can be overloaded with numerous sets of parameters. Because the compiler statically binds the method call to a particular method, this is referred to as static polymorphism. 

    A subclass inside an inheritance hierarchy can override a method of a superclass. The JVM will always call the overridden function even if you cast the subclass to its superclass before instantiating it. It's known as dynamic polymorphism. 

    The user can modify the tested classes and scripts thanks to polymorphism. It helps to expand the programming on its own. Additionally, it enables the user to keep many variables of various types, such as double, Float, Int, or Long, in a single variable, making it easier to find and use. 

    A Programming Certification is a bonus that will make you stand out from the rest. Proper training from an institute such as KnowledgeHut will help you gain skills that are relevant and in demand in the industry. is a bonus that will make you stand out from the rest. Proper training from an institute such as KnowledgeHut will help you gain skills that are relevant and in demand in the industry.

    Frequently Asked Questions (FAQs)

    1What is the role of polymorphism?

    We can carry out a single activity in various ways because of polymorphism. To put it another way, polymorphism enables the definition of a single interface with various implementations. It implies many forms because "poly" means many, and "morphs" means forms. 

    2Why is polymorphism important? 

    We can carry out a single activity in various ways because of polymorphism. To put it another way, polymorphism enables the definition of a single interface with various implementations.

    3What is polymorphism in data structure?

    In terms of programming, polymorphism refers to the reuse of a single code across various contexts. More specifically, it refers to a program's capacity to handle objects in various ways according to their data type or class.

    Profile

    Ramulu Enugurthi

    Blog Author

    Ramulu Enugurthi, a distinguished computer science expert with an M.Tech from IIT Madras, brings over 15 years of software development excellence. Their versatile career spans gaming, fintech, e-commerce, fashion commerce, mobility, and edtech, showcasing adaptability in multifaceted domains. Proficient in building distributed and microservices architectures, Ramulu is renowned for tackling modern tech challenges innovatively. Beyond technical prowess, he is a mentor, sharing invaluable insights with the next generation of developers. Ramulu's journey of growth, innovation, and unwavering commitment to excellence continues to inspire aspiring technologists.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Programming Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon