Saturday, February 6, 2016

What is overloading?

What is overloading?

Java supports polymorphism i.e with one name multiple functionalities. Java can acheive this by either overloading or overriding.

Overloading is when inside a class we might have multiple methods to which different arguments are passed. Here different argument means 2 variables which is not having any is-a relationship between them.

Lets take an example to understand it better.

Class A{
void display(String str){
 Syestem.out.println(str);
}
void display(int i){
 Syestem.out.println(i);
}
}

Here 2 methods display(...) are overloaded method because their arguments are different.

Here are the rules to make 2 methods overloaded:
1. Methods must take its arguments different. Here if a method is taking object of Class A then another method which is taking object of [Class B extends A] then it is not allowed.
2. Overloading can be done with its super class methods.
3. Overloading allows 2 methods to throw different Exceptions.
4. Overloading can change return types.
5. Overloading can change the access modifiers of the methods in any combination.

No comments:

Post a Comment