What are the types of polymorphism in java
Polymorphism in Java is the task that performs a single action in different ways.
So, languages that do not support polymorphism are not ‘Object-Oriented Languages’, but ‘Object-Based Languages’. Ada, for instance, is one such language. Since Java supports polymorphism, it is an Object Oriented Language.
Polymorphism in Java is the ability of a single method or class to take on multiple forms. It allows objects of different types to be treated as objects of a common type, providing a way to achieve flexibility and abstraction in programming. Polymorphism is achieved through two mechanisms in Java: method overloading and method overriding.
types of polymorphism in java
In Java, polymorphism is achieved through two main types: compile-time polymorphism (also known as static or method overloading) and runtime polymorphism (also known as dynamic or method overriding). Let’s explore both types in detail:
1. Compile-Time Polymorphism (Method Overloading):
- Method Overloading: It involves defining multiple methods with the same name in the same class, but with different parameter types, number of parameters, or both.
- operator overloading: Operator overloading in Java refers to the ability to define and use operators in a way that extends their functionality beyond their standard behavior. Unlike some other programming languages like C++, Java does not support operator overloading for custom classes. However, Java does have a set of predefined operators that can be used with built-in types.
Example of ‘Method Overloading’
Example of ‘Operator Overloading‘
2. Runtime Polymorphism (Method Overriding):
- Method Overriding: It involves providing a specific implementation for a method in a subclass that is already defined in its superclass.
- Determined at Runtime: The decision about which method to call is made at runtime based on the actual type of the object. It is also known as late or dynamic binding.
Note: Runtime polymorphism is achieved through the use of the
@Override annotation to indicate that a method in a subclass is intended to override a method in its superclass.
Both compile-time polymorphism (method overloading) and runtime polymorphism (method overriding) contribute to the concept of polymorphism in Java, allowing for flexibility and abstraction in object-oriented programming.