Overload of methods that Java must learn and learn

1、 Method overload

The method name is the same, but the parameters are different. This is overload.

The so-called parameters are different. There are two main points: first, the number of parameters is different, and second, the type of parameters is different. As long as one of these two aspects is different, it can constitute a method overload.

Here, the two Max methods with void modifier have the same name, but their parameter types are different, so they can constitute an overload. The int max (int a, int b) method and void max (int a, int b) method do not constitute overloading. Now they are two methods with duplicate names. It is not allowed to declare two methods with duplicate names in a class, and the compilation will make an error. The method name is the same, the parameter type is the same, and only the return value is different. This does not constitute an overload, because a method can be called in this way, and its return value can not be used when calling a method. Therefore, when calling these two methods, the integer data is passed in. Because both methods have the same name and the same parameter type, So the compiler cannot tell which method to call. The deep-seated reason for overloading: as long as the compiler can distinguish the two methods and know which one to call when calling, the two methods constitute overloading without confusion.

Look at the following two methods:

These two methods can also constitute overloads, because the compiler will treat an integer as an int as soon as it sees it. So when passing in integers, the compiler first calls the method max (int a, int b). To call the max (short a, short b) method, write this in the main method:

2、 Overloading of construction methods

Like normal methods, constructors can also be overloaded

The above is a detailed explanation of the overloading of Java methods. I hope it will be helpful to your study.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>