
Difference between Method/Function Overloading and Overriding (Polymorphism)
Polymorphism, a foundational concept in object-oriented programming (OOP), allows methods or functions to process objects differently based on their data type or class. In Java, polymorphism enables one interface to be used for a general class of actions, allowing a program to behave dynamically depending on the context. This tutorial explains polymorphism, covers its types and benefits, and illustrates its implementation in Java.
What is Polymorphism?
Contents
- What is Polymorphism?
- 1. Compile-Time Polymorphism (Method Overloading)
- Example of Method Overloading
- 2. Run-time polymorphism (Method Overriding)
- Example of Method Overriding
- Upcasting and Dynamic Method Dispatch
- Benefits of Polymorphism
- Real-World Example: A Payment System
- Differences Between Method Overloading and Method Overriding
- Polymorphism in Interfaces
- Best Practices for Using Polymorphism in Java
- Summary
- Share this:
- Like this:
- Related
Polymorphism, from Greek words meaning “many forms,” refers to the ability of an object to take on multiple forms. It allows a single function or method to work differently based on the object calling it, which enhances code flexibility and reusability. In Java, polymorphism can be achieved through:
- Method Overloading (Compile-Time Polymorphism)
- Method Overriding (Run-Time Polymorphism)
1. Compile-Time Polymorphism (Method Overloading)
In function overloading, multiple methods in the same class have the same name but different parameter lists. The compiler determines which method to call based on the method signature. This decision is made during compilation, hence the term “compile-time polymorphism.”
Example of Method Overloading
class Calculator {
// Method to add two integers
int add(int a, int b) {
return a + b;
}
// Method to add three integers
int add(int a, int b, int c) {
return a + b + c;
}
// Method to add two double values
double add(double a, double b) {
return a + b;
}
}
public class TestCalculator {
public static void main(String[] args) {
Calculator calculator = new Calculator();
System.out.println("Add two integers: " + calculator.add(5, 10));
System.out.println("Add three integers: " + calculator.add(5, 10, 15));
System.out.println("Add two doubles: " + calculator.add(5.5, 10.5));
}
}
In this example:
- The
Calculator
class defines threeadd
methods with different parameters. - The compiler selects the correct method based on the argument type and number, providing flexibility without altering method names.
2. Run-time polymorphism (Method Overriding)
In method overriding, a subclass provides a specific implementation of a method that is already defined in its superclass. This type of polymorphism is resolved during runtime. Run-time polymorphism supports the concept of “one interface, many methods” by allowing different subclasses to provide their unique implementations of a superclass method.
Example of Method Overriding
class Car {
void drive() {
System.out.println("The car is driving.");
}
}
class Sedan extends Car {
@Override
void drive() {
System.out.println("The Sedan run smoothly on the highway.");
}
}
class SUV extends Car {
@Override
void drive() {
System.out.println("The SUV run smoothly on the highway.");
}
}
class SportsCar extends Car {
@Override
void drive() {
System.out.println("The SportsCar zooms at high speed on the track.");
}
}
public class CarTest {
public static void main(String[] args) {
Car mySedan = new Sedan();
Car mySUV = new SUV();
Car mySportsCar = new SportsCar();
mySedan.drive();
mySUV.drive();
mySportsCar.drive();
}
}
In this example:
- The
Car
superclass provides a genericdrive
method. Each subclass (Sedan, SUV, and SportsCar) overrides drive with its unique behaviour. Using a Car reference for different car types enables polymorphic behaviour at runtime through dynamic method dispatch.
Upcasting and Dynamic Method Dispatch
Java uses upcasting to handle method calls at runtime. When a superclass reference points to a subclass object, it can call overridden methods in the subclass based on the object’s actual type. This process is known as dynamic method dispatch and is a key feature of runtime polymorphism.
Car Suv = new Car(); // Upcasting
Suv.drive(); // Calls drive method due to dynamic method dispatch
Benefits of Polymorphism
Code Reusability: Reusable code is a major advantage of polymorphism. Methods with the same name can work with different types or classes, reducing code redundancy.
Extensibility: New classes and methods can be added with minimal changes to existing code, as polymorphic behavior is inherently adaptable.
Maintainability: A polymorphic approach improves code organization, making the codebase easier to manage and maintain.
Real-World Example: A Payment System
Consider a payment system with different payment methods like CreditCard and PayPal. Polymorphism allows creating a general Payment
interface that can handle different payment methods dynamically.
interface Payment {
void makePayment(double amount);
}
class CreditCard implements Payment {
@Override
public void makePayment(double amount) {
System.out.println("Paid " + amount + " with Credit Card.");
}
}
class PayPal implements Payment {
@Override
public void makePayment(double amount) {
System.out.println("Paid " + amount + " via PayPal.");
}
}
public class PaymentSystem {
public static void main(String[] args) {
Payment payment1 = new CreditCard();
Payment payment2 = new PayPal();
payment1.makePayment(100.00);
payment2.makePayment(250.00);
}
}
In this system:
- Both
CreditCard
andPayPal
classes implement thePayment
interface. - By using the
Payment
reference, the program dynamically decides the payment method, showcasing polymorphism in action.
Differences Between Method Overloading and Method Overriding
Aspect | Method Overloading | Method Overriding |
---|---|---|
Purpose | To define multiple methods with the same name but different parameters. | To provide a specific implementation in a subclass for a superclass method. |
Binding | Compile-time | Run-time |
Scope | Within the same class | Across a superclass-subclass hierarchy |
Return Type | Can differ | Must be the same or covariant |
Polymorphism in Interfaces
Java interfaces support polymorphism by allowing a class to implement multiple interfaces. This approach can lead to flexible and extensible designs.
interface Drawable {
void draw();
}
class Circle implements Drawable {
public void draw() {
System.out.println("Drawing a Circle");
}
}
class Square implements Drawable {
public void draw() {
System.out.println("Drawing a Square");
}
}
public class ShapeTest {
public static void main(String[] args) {
Drawable shape1 = new Circle();
Drawable shape2 = new Square();
shape1.draw(); // Outputs "Drawing a Circle"
shape2.draw(); // Outputs "Drawing a Square"
}
}
Best Practices for Using Polymorphism in Java
- Favor Interfaces: Use interfaces to define generic behaviors, allowing multiple implementations and promoting extensibility.
- Choose Clear Method Names: For overloaded methods, make parameter types and method purposes clear to avoid confusion.
- Use
@Override
Annotation: This helps ensure methods are correctly overridden and improves code readability. - Keep Methods Specific to Purpose: Avoid excessive method overloading that could reduce code clarity.
Visit the detailed presentation.
Summary
Polymorphism in Java is a robust tool for creating flexible, reusable, and maintainable code. By supporting both compile-time (method overloading) and run-time (method overriding) polymorphism, Java allows methods to adapt based on context, empowering developers to create more dynamic applications.
This detailed tutorial follows your comprehensive guide’s structure by focusing on real-world examples, in-depth explanations, and coding illustrations.
76 thoughts on “Difference between Method/Function Overloading and Overriding (Polymorphism)”
Good post however , I was wanting to know if you could write a litte more on this topic? I’d be very thankful if you could elaborate a little bit more. Thank you! http://www.kayswell.com
Hi there, its fastidious article concerning media print, we all be aware of media is a great source of data. http://www.kayswell.com
It’s not my first time to visit this web site, i am browsing this website dailly and get good facts from here all the time. http://www.kayswell.com
It’s great that you are getting ideas from this article as well as from our argument made at this time. http://www.kayswell.com
Oh my goodness! Incredible article dude! Many thanks, However I am experiencing problems with your RSS. I don’t understand the reason why I cannot join it. Is there anybody having the same RSS issues? Anyone that knows the solution will you kindly respond? Thanx!! http://www.kayswell.com
Hi there, its fastidious article concerning media print, we all be aware of media is a great source of data. http://www.kayswell.com
We’re a group of volunteers and starting a new scheme in our community. Your website offered us with helpful information to work on. You’ve done a formidable task and our whole community will be thankful to you. http://www.kayswell.com
Hi there, its fastidious article concerning media print, we all be aware of media is a great source of data. http://www.kayswell.com
I really like what you guys tend to be up too. This kind of clever work and reporting! Keep up the amazing works guys I’ve added you guys to my blogroll. http://www.kayswell.com
Have you ever thought about adding a little bit more than just your articles? I mean, what you say is valuable and everything. Nevertheless think about if you added some great pictures or video clips to give your posts more, http://www.kayswell.com“pop”! Your content is excellent but with pics and videos, this site could certainly be one of the best in its niche. Terrific blog!
Greetings! Very helpful advice in this particular post! It is the little changes that produce the biggest changes. Thanks a lot for sharing! http://www.kayswell.com
I’d like to thank you for the efforts you have put in writing this blog.I’m hoping to check out the same high-grade content from you later on as well. In truth, http://www.kayswell.com your creative writing abilities has motivated me to get my very own website now 😉
Do you mind if I quote a few of your articles as long as I provide credit and sources back to your website? My website is in the exact same area of interest as yours and my visitors would definitely benefit from some of the information you provide here. http://www.kayswell.com
Hi, i think that i saw you visited my weblog so i came to “return the favor”.I am trying to find things to enhance my site!I suppose its ok to use some of your ideas!! http://www.kayswell.com
Hey there fantastic blog! Does running a blog similar http://www.kayswell.com
You’re so interesting! I don’t suppose I have read something like this before. So nice to discover another person with a few genuine thoughts on this subject. Seriously.. many thanks for starting this up. This web site is something that’s needed on the web, someone with a little originality! http://www.kayswell.com
Thank you for any other fantastic article. The place else may anyone get that type of info in such an ideal means of writing? I have a presentation subsequent week, and I’m at the search for such information. http://www.kayswell.com
It’s in point of fact a great and useful piece of info.I am glad that you just shared this useful info with us.Please keep us informed like this. Thanks for sharing. http://www.kayswell.com
Nice answers in return of this matter with firm arguments and telling everything concerning that. http://www.kayswell.com
I’m extremely impressed with your writing skills as well as with the layout on your weblog. Is this a paid theme or did you customize it yourself? Anyway keep up the excellent quality writing,it is rare to see a nice blog like this one today. http://www.kayswell.com
Its like you read my mind! You appear to know so much about this, like you wrote the book in it or something. http://www.kayswell.com
It’s great that you are getting ideas from this article as well as from our argument made at this time.
Ahaa, its pleasant dialogue on the topic of this piece of writing here at this web site, I have read all that,so at this time me also commenting at this place.
If you want to increase your experience just keep visiting this site and be updated with the most up-to-date news update posted here. http://www.kayswell.com
It’s actually very complex in this busy life to listen news on TV, so I just use world wide web for that reason, and get the newest news. http://www.kayswell.com
Right now it sounds like WordPress is the preferred blogging platform out there right now. (from what I’ve read) Is that what you are using on your blog? http://www.kayswell.com
I’m not that much of a internet reader to be honest but your blogs really nice, keep it up! I’ll go ahead and bookmark your site to come back down the road. Many thanks http://www.kayswell.com
I just like the valuable information you provide on your articles.I’ll bookmark your blog and test again here frequently. I’m quite certain I’ll be informed plenty of new stuff proper right here! http://www.kayswell.com Good luck for the next!
Hey there! Would you mind if I share your blog with my myspace group? There’s a lot of people that I think would really enjoy your content. Please let me know. Thanks http://www.kayswell.com
Its like you read my mind! You appear to know so much about this, like you wrote the book in it or something. http://www.kayswell.com
Hello! I just wanted to ask if you ever have any problems with hackers? My last blog (wordpress) was hacked and I ended up losing months of hard work due to no back up. Do you have any methods to prevent hackers? http://www.kayswell.com
You actually make it seem so easy with your presentation but I find this matter to be actually something that I think I would never understand. It seems too complex and very broad for me. I’m looking forward for your next post, I will try to get the hang of it! http://www.kayswell.com
Thanks for your help and for writing this post. It’s been great. http://www.kayswell.com
I am genuinely thankful to the owner of this web page who has shared this fantastic post at here. http://www.kayswell.com
Way cool! Some extremely valid points! I appreciate you penning this write-up and also the rest of the website is really good. http://www.kayswell.com
First off I would like to say superb blog! I had a quick question which I’d like to ask if you don’t mind. I was interested to find out how you center yourself and clear your thoughts before writing. http://www.kayswell.com I have had a difficult time clearing my mind in getting my ideas out there.I truly do take pleasure in writing but it just seems like the first 10 to 15 minutes are
It’s a pity you don’t have a donate button! I’d definitely donate to this fantastic blog! I guess for now i’ll settle for bookmarking and adding your RSS feed to my Google account. I look forward to new updates and will share this blog with my Facebook group. Talk soon! http://www.kayswell.com
Appreciation to my father who informed me on the topic of this web site, this website is really amazing. http://www.kayswell.com
I am really impressed with your writing skills as well as with the layout on your blog. Is this a paid theme or did you modify it yourself? Anyway keep up the nice quality writing, it is rare to see a nice blog like this one nowadays. http://www.kayswell.com
It’s impressive that you are getting thoughts from this piece of writing as well as from our argument made at this time. http://www.kayswell.com
constantly i used to read smaller articles or reviews that also clear their motive,and that is also happening with this piece of writing which I am reading here. http://www.kayswell.com
Wonderful goods from you, man. I’ve understand your stuff previous to and you’re just too excellent.I really like what you have acquired here, certainly likewhat you are stating and the way in which you say it.You make it entertaining and you still care for to keep it wise.I cant wait to read much more from you. http://www.kayswell.com This is actually a wonderful site.
Hello, i read your blog occasionally and i own a similar one and i was just curious if you get a lot of spam feedback? If so how do you stop it, any plugin or anything you can recommend? I get so much lately it’s driving me insane so any help is very much appreciated. http://www.kayswell.com
Hello! I just wanted to ask if you ever have any problems with hackers? My last blog (wordpress) was hacked and I ended up losing months of hard work due to no back up. Do you have any methods to prevent hackers? http://www.kayswell.com
I am genuinely thankful to the owner of this web page who has shared this fantastic post at here. http://www.kayswell.com
Aw, this was a very nice post. Taking the time and actual effort to create a great article… but what can I say… I hesitate a whole lot and never seem to get nearly anything done. http://www.kayswell.com
I constantly emailed this blog post page to all my contacts, for the reason that if like to read it after that my friends will too. http://www.kayswell.com
It’s amazing to pay a visit this site and reading the views of all friends regarding this paragraph, while I am also keen of getting know-how. http://www.kayswell.com
Hello to all, the contents existing at this web page are genuinely remarkable for people knowledge, well, keep up the good work fellows. http://www.kayswell.com
This is my first time visit at here and i am actually happy to read everthing at alone place. http://www.kayswell.com
Hello everyone, it’s my first pay a visit at this website, and paragraph is in fact fruitful in support of me, keep up posting these types of articles. http://www.kayswell.com
I’m not sure if this is a format issue or something to do with internet browser compatibility but I figured I’d post to let you know. The style and design look great though! Hope you get the issue fixed soon. Many thanks http://www.kayswell.com
Heya i am for the first time here. I found this board and I to find It truly helpful & it helped me out much. I hope to offer one thing back and help others like you aided me. http://www.kayswell.com
It’s great that you are getting ideas from this article as well as from our argument made at this time. http://www.kayswell.com
Ahaa, its good dialogue regarding this article at this place at this website, I have read all that, so at this time me also commenting here. http://www.kayswell.com
Thank you for the auspicious writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! By the way, how could we communicate? http://www.kayswell.com
Hello everyone, it’s my first pay a visit at this website, and paragraph is in fact fruitful in support of me, keep up posting these types of articles. http://www.kayswell.com
I am not sure where you are getting your info, but good topic. I needs to spend some time learning more or understanding more. Thanks for excellent info I was looking for this information for my mission. http://www.kayswell.com
I used to be able to find good advice from your blog articles. http://www.ifashionstyles.com
If some one needs to be updated with latest technologies therefore he must be go to see this web site and be up to date every day. http://www.kayswell.com
If some one needs to be updated with latest technologies therefore he must be go to see this web site and be up to date every day. http://www.hairstylesvip.com
When someone writes an piece of writing he/she keeps the thought of a user in his/her brain that how a user can know it. So that’s why this paragraph is outstdanding. http://www.kayswell.com
Hi there to all, for the reason that I am truly keen of reading this website’s post to be updated daily. It carries fastidious data. http://www.kayswell.com
Hey there fantastic blog! Does running a blog similar http://www.kayswell.com
Hello there, You’ve done a great job. I will definitely digg it and personally recommend to my friends. I am confident they will be benefited from this website. http://www.ifashionstyles.com
Hi there, everything is going sound here and ofcourse every one is sharing data, that’s really good, keep up writing. http://www.kayswell.com
This is very attention-grabbing, You are an excessively professional blogger.I’ve joined your feed and stay up for in quest of extra of your fantastic post. http://www.kayswell.com Also, I have shared your web site in my social networks。
It’s impressive that you are getting thoughts from this piece of writing as well as from our argument made at this time. http://www.ifashionstyles.com
Thanks for revealing your ideas here. The other element is that when a problem comes up with a laptop motherboard, folks should not consider the risk associated with repairing the item themselves for if it is not done properly it can lead to permanent damage to all the laptop. It’s usually safe just to approach your dealer of a laptop for any repair of the motherboard. They’ve technicians with an competence in dealing with notebook computer motherboard issues and can have the right diagnosis and execute repairs.
You really make it appear really easy together with your presentation however I in finding this topic to be actually something that I believe I might by no means understand. It sort of feels too complicated and very extensive for me. I’m looking forward on your subsequent submit, I will attempt to get the hang of it!
It’s in point of fact a great and useful piece of info.I am glad that you just shared this useful info with us.Please keep us informed like this. Thanks for sharing. http://www.kayswell.com
Its like you read my mind! You appear to know so much about this, like you wrote the book in it or something. http://www.kayswell.com
I was just looking for this info for a while. After 6 hours of continuous Googleing, finally I got it in your web site. I wonder what is the lack of Google strategy that don’t rank this kind of informative web sites in top of the list. Normally the top websites are full of garbage.
Its like you read my mind! You appear to know so much about this, like you wrote the book in it or something. http://www.hairstylesvip.com
I have been exploring for a little bit for any high-quality articles or blog posts on this sort of area . Exploring in Yahoo I at last stumbled upon this web site. Reading this information So i抦 happy to convey that I have a very good uncanny feeling I discovered just what I needed. I most certainly will make sure to don抰 forget this site and give it a look regularly.
Hi there, just became alert to your blog through Google,and found that it is truly informative. I am gonna watch outfor brussels. I’ll be grateful if you continue this in future.Lots of people will be benefited from your writing.Cheers! http://www.kayswell.com