🦋Polymorphism
Last updated
Last updated
Polymorphism means "many forms". It allows objects to be accessed in many different ways, depending on their type.
In Java, polymorphism manifests in two primary forms:
Method overloading
Method overriding
Method overloading allows different methods to have the same name, as long as they have different signatures.
This allows the add
method to be used in different ways based on the parameters passed. The compiler can differentiate between the methods based on the number and type of arguments.
Method overloading is a key aspect of polymorphism in Java. It allows the same method name to be used flexibly for multiple scenarios.
Method overriding occurs when a child class provides its own implementation of a method already defined in the parent class.
Output:
This allows subclasses like Cat to give their own specific implementations, maintaining polymorphic behavior. Even though animal
is declared as the parent Animal class, it prints "Meow" based on the overridden method in the Cat subclass.
Polymorphism in Java works through following certain rules around method overloading and overriding.
Method overloading has the following rules:
The methods must have the same name
The parameters must be different - different number of parameters, different types, or both
The return type can be different
Overloaded methods can throw different exceptions
For example:
The add()
method is overloaded by having different parameter types.
Some key rules for method overriding are:
The method must have the same signature (name + parameters)
The return type must be the same or a subclass
The access modifier cannot be more restrictive than the parent
The overridden method can throw only the same or subclass exceptions
For example:
The getName()
method is properly overridden in Car
by having the same method signature and return type.
So polymorphism works by following these rules around overloading and overriding methods in Java.
Polymorphism allows one thing to be accessed in different forms
Method overloading has the same method name but different signatures
Method overriding provides specific implementations in subclasses
Polymorphism enables very reusable and extendable code
So in essence, polymorphism allows dynamic and flexible programming!
Polymorphism allows things like methods to take on different forms and behaviors based on specific object types. It enables code reuse and extendability.
Like a shape that can be a circle, square or triangle polymorphically. Same shape, different forms!