Home >Java >javaTutorial >What's the difference between method overloading and overriding?

What's the difference between method overloading and overriding?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-09 12:17:02551browse

What's the difference between method overloading and overriding?

Method Overloading vs. Overriding

Method overloading and overriding are two distinct concepts in object-oriented programming that share a commonality: they both involve redefining a method in a class. However, their purpose and implementation differ significantly.

Method Overloading

Method overloading occurs when a class declares multiple methods with the same name but different argument lists. It enables a single method to perform different tasks based on the type and number of arguments provided. For example:

public void foo(int a) { ... }
public void foo(int a, float b) { ... }

In this example, the class defines two versions of the foo method that differ in the number of arguments they take. When calling the foo method, the compiler determines which version to invoke based on the arguments passed.

Method Overriding

Method overriding, on the other hand, involves redefining a method with the same argument list in a subclass. Unlike overloading, overriding occurs when a child class wants to provide its own implementation of a method inherited from the parent class. To do so, the child class must use the @Override annotation to indicate that it is overriding an existing method:

class Parent {
    void foo(double d) { ... }
}

class Child extends Parent {

    @Override
    void foo(double d) { ... }
}

In this example, the Child class overrides the foo method inherited from the Parent class. When an instance of the Child class calls the foo method, the overridden implementation in the Child class is executed.

The above is the detailed content of What's the difference between method overloading and overriding?. 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