Home  >  Article  >  Java  >  What's the difference between method overloading and overriding in OOP?

What's the difference between method overloading and overriding in OOP?

Barbara Streisand
Barbara StreisandOriginal
2024-11-06 16:13:03735browse

What's the difference between method overloading and overriding in OOP?

Understanding Method Overloading vs Overriding

Method overloading and overriding are two distinct concepts in object-oriented programming that influence how methods are invoked and implemented within a class hierarchy.

Method Overloading

Method overloading refers to the ability to define multiple methods in the same class with the same name but different argument lists. This allows you to create methods that perform similar operations with different variations of input parameters. For example:

class Math {
    int add(int a, int b) { ... }
    double add(double a, double b) { ... }
}

Method Overriding

Method overriding occurs when a subclass defines a method with the same name and argument list as a method in its superclass. When an object of the subclass calls the overridden method, the implementation from the subclass is invoked, effectively replacing the original implementation from the superclass. The @Override annotation is often used to indicate that a method is intended to override a superclass method. For example:

class Animal {
    void makeSound() { ... }
}

class Dog extends Animal {
    @Override
    void makeSound() { ... } // Override the makeSound() method from the Animal class
}

The above is the detailed content of What's the difference between method overloading and overriding in OOP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn