English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Java

Contrôle de flux Java

Java tableau

Java orienté objet (I)

Java orienté objet (II)

Java orienté objet (III)

Gestion des exceptions Java

Java Liste (List)

Java Queue (file d'attente)

Java Map

Java Set

Java entrée/sortie (I/O)

Reader Java/Writer

Autres sujets Java

Surcharge de méthode Java

Dans cet article, vous découvrirez la surcharge de méthode et comment l'implémenter en Java à l'aide d'exemples.

Dans Java, si deux ou plusieursLes méthodesSi les paramètres diffèrent (différents nombres de paramètres, différents types de paramètres ou les deux), ils peuvent avoir le même nom. Ces méthodes sont appelées méthodes surchargées, et cette fonctionnalité est appelée surcharge de méthode. Par exemple :

void func() { ... }
void func(int a) { ... }
float func(double a) { ... }
float func(int a, float b) { ... }

Ici, la méthode func() est surchargée. Ces méthodes ont le même nom, mais acceptent des paramètres différents.

Veuillez noter que les types de retour de ces méthodes diffèrent. Les méthodes surchargées peuvent avoir des types de retour différents, ou elles peuvent ne pas avoir de types de retour différents, mais elles doivent accepter des paramètres différents.

为什么方法重载?

假设您必须执行给定数字的加法运算,但是可以有任意数量的参数(为简单起见,可以说2个或3个参数)。

为了完成任务,可以分别为两个和三个参数创建两个方法sum2num(int, int)和sum3num(int, int, int)。但是,其他程序员以及您将来可能会感到困惑,因为这两种方法的行为相同,但名称不同。

完成此任务的更好方法是重载方法。并且,根据传递的参数,调用其中一个重载方法。这有助于提高程序的可读性。

如何在Java中执行方法重载?

以下是执行方法重载的不同方法:

1.通过更改参数数量来重载

class MethodOverloading {
    private static void display(int a){
        System.out.println("参数: " + a);
    }
    private static void display(int a, int b){
        System.out.println("参数: " + a + " 和 " + b);
    }
    public static void main(String[] args) {
        display(1);
        display(1, 4);
    }
}

输出:

参数: 1
参数: 1 和 4

2.通过更改参数的数据类型

class MethodOverloading {
    //此方法接受int
    private static void display(int a){
        System.out.println("得到了整数数据.");
    }
    //此方法接受String对象
    private static void display(String a){
        System.out.println("得到了String对象。");
    }
    public static void main(String[] args) {
        display(1);
        display("Hello");
    }
}

输出:

得到了整数数据
得到了String对象。

在这里,两个重载方法都接受一个参数。但是,一个接受int类型的参数,而另一个接受String对象。

让我们看一个真实的例子:

class HelperService {
    private String formatNumber(int value) {
        return String.format("%d", value);
    }
    private String formatNumber(double value) {
        return String.format("%.3f", value);
    }
    private String formatNumber(String value) {
        return String.format("%.2f", Double.parseDouble(value));
    }
    public static void main(String[] args) {
        HelperService hs = new HelperService();
        System.out.println(hs.formatNumber(500));
        System.out.println(hs.formatNumber(89.9934))
        System.out.println(hs.formatNumber("550"));
    }
}

When running this program, the output is:

500
89.993
550.00

NoteIn Java, you can also overload constructors in a way similar to methods.

Recommended related: Java constructor overloading

Notes

  • If two or more methods accept different parameters, they can have the same name in the same class. This feature is called method overloading.

  • Method overloading can be achieved in the following ways:

    • Change the number of parameters.

    • Or change the data type of the parameters.

  • Method overloading cannot be achieved by simply changing the return type of the method.