Difference between Method/Function Overloading and Overriding (Polymorphism)

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:

  1. Method Overloading (Compile-Time Polymorphism)
  2. 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 three add 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 generic drive 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 and PayPal classes implement the Payment interface.
  • By using the Payment reference, the program dynamically decides the payment method, showcasing polymorphism in action.

Differences Between Method Overloading and Method Overriding

AspectMethod OverloadingMethod Overriding
PurposeTo define multiple methods with the same name but different parameters.To provide a specific implementation in a subclass for a superclass method.
BindingCompile-timeRun-time
ScopeWithin the same classAcross a superclass-subclass hierarchy
Return TypeCan differMust 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

  1. Favor Interfaces: Use interfaces to define generic behaviors, allowing multiple implementations and promoting extensibility.
  2. Choose Clear Method Names: For overloaded methods, make parameter types and method purposes clear to avoid confusion.
  3. Use @Override Annotation: This helps ensure methods are correctly overridden and improves code readability.
  4. 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)

  1. 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.

  2. 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!

  3. 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

  4. 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

  5. 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

  6. 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

  7. 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

  8. 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

  9. 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

  10. 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

  11. 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

  12. 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

  13. 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

  14. 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

  15. 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/

  16. 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

  17. 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

  18. 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.

  19. 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

  20. 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

  21. 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

  22. 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

  23. 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..

  24. 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!

  25. 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

  26. 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.

  27. 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

  28. 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

  29. 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

  30. 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!

Leave a Reply

Your email address will not be published. Required fields are marked *