I am still a learner of core java. I want to understand the polymorphism concepts here.
I have understood the overriding and have a question on overloading.
Why do we call it as method overloading though we are calling different methods(i mean only the arguments are different.) .
I simply feel that it is quite simple as calling different methods which bind during compile time and only difference here is that i have a same method name..
Class A {
method A(int i){}
method A(int i, int B){}
}
Please share your inputs.
With method overloading you're calling "the same method", only with different parameters and/or different output. This makes it easy for you to write methods with the same core functionality but with different input parameters. Example:
public int Sum(int a, int b) {
return a + b;
}
public double Sum (double a, double b) {
return a + b;
}
Otherwise you would have methods like SumInt(...) and SumDouble(...) and so on. You can also have 2 methods with the same return type but different input and still use overloading for ease:
public int Sum(int a, int b) {
return Sum(a, b, 0);
}
public int Sum (int a, int b, int c) {
return a + b + c;
}
This way, you only have one place with al the logic and all the other methods just call the one method with all the logic, only with different parameters. And then there's also constructor overloading. For example you can have an empty constructor in which you set some default values and you can have a constructor where you can set the values yourself:
//Without overloading you'll have to set the properties after instantiating the class
public MyClass() {
this.PropertyOne = "1";
this.PropertyTwo = 2;
}
//usage:
MyClass instance = new MyClass();
//now theproperties are already set to "1" and 2, wheter you like it or not
//here you change the values
instance.PropertyOne = "...";
instance.PropertyTwo = 0;
//With constructor overloading you have this
public MyClass() {
this("One", 2);
}
public MyClass(string propOne, int propTwo) {
this.PropertyOne = propOne;
this.PropertyTwo = propTwo;
}
//usage:
MyClass instance = new MyClass("MyValue", 1000);
//if you call MyClass() the default values STILL will be set :)
The second way gives you more possibilities, not? And it makes it a lot more easy to change your code. Hope this helps!