Polymorphism,Overloading v/s Overriding

Polymorphism! One name.. but many functions.

Polymorphism can be dynamic or passive.
Dynamic as in terms of... the object knows which method to actually call when the JVM is up
Passive polymorphism is when which method to call is already know when the classes are compiled.

Example:
We have a class A. B extends A.

A has a method :
public int getA(){
return 1;
}

B also has this method, but the value returned is different:
public int getA(){
return 2;
}

In our main class, we create objects of A and B, always keeping reference to the object as A.
So, our main looks like:

A a = new A();
A b = new B();

System.out.println("a.getA() : "+a.getA());
System.out.println("b.getA() : "+b.getA());


Output:
a.getA() : 1
a.getB() : 2

This is dynamic polymorphism, or overriding.
If we carefully see, the method signature is the same!!!!
IMP:
1. access modifier should be the same OR default can become protected, protected can be public but not otherwise.
2. Return type should be the same OR can be a subclass,
eg: public A getA() can become public B getA() but not otherwise.
3. the method name and the parameters should be the same
4. Exceptions!!! You cannot declare any new type of checked exception

Lets look at passive polymorphism or overloading.

In overloading, just the method name should be the same.

Lets again have our two class, A and B(extends A).

class A{

public int getA(){
//Body
}

public int getA(String param){ //Overloading method getA()
//Body
}

}



class B{

public int getA(){ //Overriding method getA() from A
//Body
}

public int getA(String param1, String param2){ //Overloading method getA() from A
//Body
}

}


Rules for overloading:
1. Method name should be same!
2. Parameters should be of different types or the no of parameters passed should be different
3. return type can be different
4. Overloading can be in subclasses or in the same class
5. No rule on Exceptions


Both of them should be used intelligently, and can help to improve the usability of the code.

Comments

Popular posts from this blog

Writing your own ejabberd Module

npm ECONNREFUSED error

Conditional Flow - Spring Batch Part 6