- In general, we can say one entity showing different behaviours at different places throughout the execution of the program is called as "polymorphism".
- Suppose if we take interface, class which implements that interface and overrides the same method in each class with different behaviours/logic. That means, the same method behaves differently in each class when we call that method.
There are two types of polymorphism
(i) compiletime polymorphism
(ii) runtime polymorphism
Compiletime polymorphism:
- Binding the method declaration to method definition based on the arguments by the compiler at the compile time is called compiletime polymorphism.
- We can achieve compiletime polymorphism with the help of method overloading.
Method overloading:
- Developing multiple methods with the same name within the same class which differs in number of arguments, order of arguments and data type of arguments is called "method overloading".
- We can overload both Static and non static methods.
- Changing the return type of overloaded methods is still considered as method overloading.
- Whenever we have to perform some common operations using different parameters then we go for method overloading.
ex: public static void m1(){}
public static void m1(int i){}
public static void m1(int i,double j){}
Runtime polymorphism:
Binding the method declaration to method definition at runtime by the JVM based on the object created is called as "runtime polymorphism".
To achieve runtime polymorphism we have to follow 3 steps.
I. Inheritance
II. Method overriding
III. Upcasting
Method overriding:
Method overriding is the inheriting the method of superclass and changing method definition according to subclass specification without changing method declaration is called as "method overriding".
- To perform method overriding inheritance is must.
- The binding of method declaration to method definition of the overridden methods is done at runtime by the JVM is called as "late binding".
- The method definition changes according to object used to call the method and hence it is called as "dynamic binding".
- Static methods cannot be overridden because static members cannot be inherited.
- If Superclass and subclass have the same static methods then it is called as "method hiding".
- Final methods cannot be overridden.
- Private methods cannot be overridden.
Note: If we use subclass object and call overridden method and you always get the overridden implementation in the subclass.
No comments:
Post a Comment