Polymorphism –
Polymorphism means – one in many forms
Creating multiple methods / functions with the same name but performing different task, same way creating single object or reference variable referring to multiple classes.
Polymorphism can be achieved in 2 ways
- Method Overloading (Compile time polymorphism or static binding)
- Method Overriding (Run time polymorphism or dynamic binding)
For details, watch here
Method Overloading
To overload methods –
- Method name should be same in the same class.
- Method signature should be unique for each method with same name, signature means
- No. of parameters
- Parameter data type
- Return type
Call to method resolved during compile time by compiler, that is why called as static or early binding or compile time polymorphism
Static binding as actual object of the class is not used to bind. [happens with in same class]
Private, static and final methods can be over loaded.
public class MethodOverloading { static void add(int a, int b) { //method signature should be unique int c = a+ b; System.out.println("Add " + a + " + " + b + " = "+ c); } static void add(double d, double e) { double c = d + e; System.out.println("Add " + d + " + " + e + " = "+ c); } static void add(String a, String b) { System.out.println(a + b); } public static String GetDetails(String d) { return d; } public static int GetDetails(int f) { return f; } public static void main(String[] args) { //System.out.println(); add(2,3); add(3.4, 5.88); add("qa", "validation"); } }
Method Overriding
To override methods –
- Method name should be same in the parent and all of it child classes
- Method signature should be same for each method with same name, signature means
- No. of parameters
- Parameter data type
- Return type
Call to method resolved during run time, that is why called as dynamic or late binding or run time polymorphism
Dynamic binding as binding happens by using actual object [call to method happens by using object]
Private, static and final methods can not be overriden.
public class MethodOverriding { public static void main(String[] args) { //BaseClass bc = new BaseClass(); BaseClass bc = new ChildClass(); bc.DispClass(); } } //Object - extreme parent class of all classes in java class BaseClass{ void DispClass() { System.out.println("BaseClass"); } } class ChildClass extends BaseClass{ void DispClass() { //method sugnature should be same as parent class System.out.println("ChildClass"); } }
What is binding –
Link between method call to method definition is called as binding.