After having understood the basics of Polymorphism and what it actually refers to in my previous post, now lets get on and try understanding Method Overloading in a little more detailed fashion.
In this post, as promised, I shall be talking about the following
Method overloading is primarily achieved as already discussed by changing the number or types of the arguments in the method. Changing the name of the arguments alone is not significant and therefore doesn’t lead to a condition wherein an overload is called a valid overload.
The following are the conditions for a method to be called a valid overloaded method in Java.
Following is a valid examples of method overloading in Java
//Class Person which implements method overloading.
class Person {
private String firstName;
private String lastName;
//Constructor
Person() {
this.firstName = “”;
this.lastName = “”;
}
// Overloaded constructor taking one string as argument.
Person(String lname) {
this.firstName = “”;
this.lastName = lname;
}
//Overloaded constructor taking two string parameters as arguments.
Person(String fname, String lname) {
this.firstName = fname;
this.lastName = lname;
}
}
Before signing off this post, i will also try explaining the reason for calling Method Overloading as Compile Time Polymorphism. Well, the reason is pretty straight, whenever you write an overloaded method and try to call it using an object of the class, you specify the arguments correctly. The compiler therefore is able to decide while compiling itself about the method to be called and therefore the name Compile Time Polymorphism.
Hope you enjoyed reading this. In the next post, i shall be talking about Method Overriding and Run Time Polymorphism.
Do stay tuned to Technofriends for more, one of the best ways of doing so if by subscribing to our feeds. You can subscribe to Technofriends feed by clicking here.
Related Reads:
Cheers
Vaibhav
You have already tagged this post. Your tags: