Introduction to Java method overloading and variable scope

The max method used above is only applicable to int data. But what if you want to get the maximum value of two floating-point data types? The solution is to create another method with the same name but different parameters, as shown in the following code:

If you pass an int parameter when calling the max method, the max method with an int parameter will be called; If the parameter of double type is passed, the max method of double type will be called, which is called method overloading; That is, two methods of a class have the same name, but have different parameter lists. The java compiler determines which method should be called based on the method signature. Method overloading can make the program clearer and easier to read. Methods that perform closely related tasks should use the same name. Overloaded methods must have different parameter lists. You can't overload methods just based on modifiers or return types. Variable scope the scope of a variable is the part of the program that the variable can be referenced. Variables defined within methods are called local variables. The scope of a local variable starts with the declaration and ends with the block containing it. Local variables must be declared before they can be used. The parameter range of the method covers the whole method. The parameter is actually a local variable. The variables declared in the initialization part of the for loop have the scope of the whole loop. However, the variable declared in the loop body is applicable from its declaration to the end of the loop body. It contains variable declarations as follows:

You can declare a local variable with the same name multiple times in different non nested blocks in a method, but you cannot declare a local variable twice in a nested block.

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
分享
二维码
< <上一篇
下一篇>>