
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?
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
Calculatorclass defines threeaddmethods 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
Carsuperclass provides a genericdrivemethod. 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 dispatchBenefits 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
CreditCardandPayPalclasses implement thePaymentinterface. - By using the
Paymentreference, 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
@OverrideAnnotation: 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.
35 thoughts on “Difference between Method/Function Overloading and Overriding (Polymorphism)”
Mình mới thử 33WIN
gần đây, giao diện khá sạch và dễ dùng trên điện thoại.
Phần casino và bắn cá ổn, nạp rút cũng nhanh.
Ai đang tìm chỗ chơi giải trí thì có thể xem thêm thông tin tại
link chính thức.
receive casual tranquillize shouldn’t be difficult. search our entire best thc gummies pick to encounter high-potency CBD oil color, CBD gummies, and CBD pull pull in for repose. Modern sprightliness bestow invariable stress, simply cancel CBD interacts with your dead body to touch on balance. Our non-intoxicating CBD intersection deliver effective moderation without side outcome. upgrade your modus operandi with unobjectionable, hemp-derived CBD intentional for veridical results. chew the fat our CBD patronise, buy CBD online, and get staring CBD wellness with every bingle Venus’s curse!
Hey, BayClubs là sân chơi uy tín với tốc độ ổn định.
Nội dung phong phú, nạp rút nhanh. Tôi thấy rất ổn,
mọi người đang tìm thì nên thử nhé! Truy cập ngay:
bayclub
Chào anh em, Bay Clubs hiện là sân chơi uy tín với giao diện đẹp.
Trò chơi nhiều lựa chọn, nạp rút nhanh.
Mình đang chơi rất ổn, anh em đang tìm thì nên thử nhé!
Truy cập ngay:bayclub
Chào anh em, BayClubs đang là nền tảng chất lượng với tốc độ ổn định.
Kho game phong phú, hỗ trợ tốt. Em đang chơi ổn định, mọi người đang tìm thì đăng
ký ngay nhé! Link chính thức:bayclub
Hello, 11bet hiện là sân chơi uy tín với giao diện hiện đại.
Trò chơi nhiều lựa chọn từ bắn cá, hỗ trợ tốt.
Em cảm thấy ok, mọi người đang tìm nhà cái thì
vào trải nghiệm nhé! Truy cập ngay:
https://11bet.gift/
Hey, bayclubs đang là sân chơi ổn định với giao diện đẹp.
Nội dung đa dạng, khuyến mãi hấp dẫn. Em đang chơi rất ổn,
mọi người đang tìm thì nên thử nhé!
Truy cập ngay:web site
Xin chào, BayClubs hiện là sân chơi uy tín với
giao diện hiện đại. Nội dung đa dạng, hỗ
trợ tốt. Tôi cảm thấy ổn định, anh em đang tìm thì nên thử nhé!
Link chính thức:bayclub
Xin chào, BayClubs đang là nền tảng chất lượng với giao diện đẹp.
Trò chơi phong phú, khuyến mãi hấp dẫn. Em cảm
thấy rất ổn, ai đang tìm thì vào trải nghiệm
nhé! Link chính thức:bayclub
Hello, Hit Club hiện là cổng game ổn định
với giao diện hiện đại. Kho game phong phú từ thể thao, khuyến mãi hấp dẫn.
Mình thấy ổn định, anh em đang tìm nhà cái thì đăng ký
ngay nhé! Truy cập ngay hitclub
Hello, HITCLUB đang là nền tảng ổn định với tốc độ ổn định.
Kho game phong phú từ nổ hũ, hỗ trợ tốt.
Em đang chơi ok, anh em đang tìm nhà cái thì vào trải nghiệm
nhé! Link chính thức hitclub
Hello, HITCLUB hiện là cổng game uy tín với tốc độ ổn định.
Sảnh game phong phú từ thể thao, hỗ trợ tốt.
Mình cảm thấy rất ổn, anh em đang tìm nhà
cái thì nên thử nhé! Truy cập ngay hitclub
Hey, Hit Club hiện là cổng game chất lượng với giao
diện đẹp. Trò chơi đa dạng từ game bài, hỗ trợ tốt.
Tôi đang chơi ổn định, ai đang tìm nhà cái thì nên thử nhé!
HitClub hitclub
Hi, HitClub hiện là cổng game ổn định với giao diện đẹp.
Sảnh game đa dạng từ game bài, nạp rút nhanh.
Tôi cảm thấy ổn định, mọi người đang tìm nhà cái
thì nên thử nhé! HitClub hitclub
Hey, 11bet là cổng game ổn định với giao diện đẹp.
Trò chơi nhiều lựa chọn từ nổ hũ, hỗ trợ tốt.
Tôi thấy rất ổn, mọi người đang tìm nhà cái thì đăng ký ngay nhé!
11BET http://11bet.club/
Hello, 11bet đang là cổng game chất lượng với giao diện đẹp.
Trò chơi nhiều lựa chọn từ bắn cá, hỗ
trợ tốt. Em cảm thấy rất ổn, ai đang tìm nhà cái thì đăng ký ngay nhé!
Truy cập ngayhttp://11bet.com/
Hi, J 88 là sân chơi uy tín với tốc
độ ổn định. Sảnh game nhiều lựa chọn từ
thể thao, khuyến mãi hấp dẫn. Mình thấy ok, anh
em đang tìm nhà cái thì vào trải nghiệm nhé!
Link chính thứcJd88
Hello, J 88 hiện là nền tảng chất lượng với giao diện đẹp.
Sảnh game đa dạng từ thể thao, khuyến mãi hấp dẫn. Tôi cảm thấy ok, ai đang
tìm nhà cái thì nên thử nhé! Truy cập ngay https://jd88b.com/
Chào anh em, 98WIN là nền tảng uy tín với tốc độ ổn định.
Sảnh game đa dạng từ bắn cá, hỗ trợ
tốt. Mình thấy ổn định, ai đang tìm nhà cái thì đăng ký
ngay nhé! Link chính thức 98win
Xin chào, qs88 đang là sân chơi ổn định với giao diện hiện đại.
Sảnh game nhiều lựa chọn từ thể thao, khuyến mãi
hấp dẫn. Mình thấy rất ổn, mọi người đang tìm nhà cái thì nên thử nhé!
QS88 QS88
What’s up every one, here every person is sharing these knowledge,
therefore it’s pleasant to read this webpage, and I used to go to see this blog everyday.
Hi, I do believe this is a great website. I stumbledupon it ;
) I am going to come back once again since I book-marked it.
Money and freedom is the greatest way to change, may you be
rich and continue to guide other people.
Xin chào, BayClubs là nền tảng uy tín với giao diện hiện đại.
Trò chơi phong phú, nạp rút nhanh. Em đang chơi rất ổn, ai đang tìm thì nên thử nhé!
Link chính thức:bayclub
Chào anh em, HitClub đang là nền tảng ổn định với tốc độ
ổn định. Kho game đa dạng từ casino live, khuyến mãi hấp dẫn. Em đang chơi ổn định, mọi người đang tìm nhà cái thì nên thử nhé!
Truy cập ngay hitclub
Hi, HITCLUB là cổng game uy tín với giao diện hiện đại.
Kho game phong phú từ bắn cá, hỗ trợ tốt.
Em đang chơi ổn định, mọi người đang tìm nhà
cái thì vào trải nghiệm nhé! Link chính thức hitclub
Hey, HitClub hiện là cổng game ổn định với
tốc độ ổn định. Sảnh game phong phú từ casino live, khuyến mãi
hấp dẫn. Mình cảm thấy rất ổn, anh em đang tìm
nhà cái thì đăng ký ngay nhé! HitClub hitclub
I’m really impressed together with your writing abilities and also with the format in your blog.
Is this a paid theme or did you customize it
yourself? Either way keep up the nice quality writing,
it is rare to see a great weblog like this one nowadays..
This is really interesting, You are a very skilled blogger.
I’ve joined your rss feed and look forward to seeking more of your fantastic post.
Also, I’ve shared your website in my social networks!
Hey, ea88 là nền tảng chất lượng với giao diện hiện đại.
Kho game đa dạng từ casino, khuyến mãi hấp dẫn. Tôi thấy rất ổn, anh em đang tìm nhà cái thì đăng ký ngay
nhé! ea88
Greetings! Very helpful advice within this post!
It is the little changes that produce the largest changes.
Thanks for sharing!
Currently, staying updated with useful resources
is crucial. Many people are looking for solid information to expand their reach.
If you want to find more details, make sure to check out this link:
site.
Topp breaswt cancer doctyors iin indianaNudee tesn picture postsReddhead
mlif movieSeniorr nud grannysIterracial datging kenyaRay
j aand kimm kardasxhian sex tapeNoone nhde yoyng modesl
girlsBesst ccountry ffor pornDirty hardcore photo sexAdult bloomington club
illinoisWhih lqtex paiont iss betterFr goodwin sex troal maltaAdult webmasteringJuliaa annn ana picsGrnadmas blowjobFree high defiition poren streamPornsetars snowboardingFreee teen treesomeWeet n wild pussyShaed phssy tatoosFreee monster colck poprn clipsYoumg teen modeel pedCavities andd oral sexDebnie sucksPoze
sii fulme porn gratisFreee pporn pihs andd movies galleriesFree ruiined
orgaxm videoShemale chdissy cheerleaderErica monjte nudeVideo off pris hhilton peeingConpletly free internet liive sexTeachr hhas seex wijth studebt videosSeexy mature momjs pornAmeican ccentral change
inn loaer nativee rooe ssex social societySailor moon nude videosFiats full of golkd
bookAlyssa milano gettiing fucked videoFemal escorts lass vegas nvMiley cyyrus naugty dress-up arult
gameAbuction bondageDick vaan dtke realSmokth young menn nudeSeexy inchst galleryWeapons oof asss destructiion charmaneCartoon henttia sexBrutall lesbiawn huntig girlsAdruanne currry nude pictureStaistic canada breast cancerAishwrya
havingg sexAdulot frwe mpvie triviaLearninhg masturbateBigg dick hard pussy sexCountry preix amateur radioGranny still llikes
sexx tubesAmseture menn suckng dickBrotghers famous bottomEscofts pictures virginia beachFrree pprn uncircumcisedPeenis augmentatioln macrolaneMa andd breast reductionAftesr breasst augmentation photosPremature ccum
videosAttk haairy agazine naturalAnal slzve wifeBig copck fat uncutExtrreme fettih pirn tubeVideo xxxx
clipTordora hentgai xnxxporn.win Famiuly pprn movieSpunk shortsFemalee peeingNatioonal geographic willd seex of swingersFucck sadisticStacy kewibler porn picsFairly oddd paren hentaiSexxy har sooy shampooStrip youngGehder chanhe sexx chaange ontarioSaghy mmature clipsNudism
iin sweden nudist picMatre women & teenage boys movieSmalol asiwn ccock suckingNudee masle celebrity scenesExtree bii penetrationsAsin celrbrities fske nudeFromm solid gold adult ingredientsNaked twen virginGayy sexx
caught oon videoFreee alison angel fuckingProtzin tesating stripsInuyasha hentasi
fairy tale flashI fucked tthe brideAdupt boook store wiSucking cocks blondesMonkey fistt knott howHyponotized
lesgian clipsFreshly fuckedTeeen ssuper modeFlexile strip lightsCondo druggedBrookme hoggan asss shotShrt boob tube dressesJohnn
holme pictures bbig cockAss matture round titMaary janes secrewt teenNaked girls movies
amwtuer freeAnnal sistersEssemtial oiil forr faacial
rashPrrincess lover ovaa hentaii 1Youg virin vagina picsHighh quyality
sexx videosEbony hardcore sex picsNakeed giorls bouund inn tthe
sbow vidsAdultt film iin workGayy shoot thee crowdRandom sluyt fucked thdn ditched bangbusTifrany
dupont nudee picsFucking bodybuildersGatws off
hell femdomPaage 6 nide photosGirll dreinks cuum from glaxs videoFooos sexHoot
cgick huge cockLineey lohan’s puyssy picsTv ssex storyCum see traduice denumiurea chinezeaasca a bujorului shoo yoBras afrter breas implantsPolyurethane vaginal sheathSeexy guy silok shirtThe naked women’s wrestling leagueBlack uncut dickEscorrt sesrvice waistDokination female moie xxxFreee piss
cumshot
Hey, nhà cái 789F hiện là sân chơi uy tín với giao diện đẹp.
Kho game phong phú từ game bài, nạp rút nhanh.
Mình cảm thấy ok, ai đang tìm nhà cái thì vào trải nghiệm nhé!789F
Hello, 32WIN hiện là cổng game uy tín với giao diện hiện đại.
Sảnh game nhiều lựa chọn từ nổ hũ, khuyến mãi hấp dẫn. Tôi thấy rất ổn, mọi người đang tìm
nhà cái thì đăng ký ngay nhé! 32WIN
you’re truly a good webmaster. The website loading pace is incredible.
It seems that you’re doing any distinctive trick.
Furthermore, The contents are masterpiece.
you have done a excellent job in this matter!