Method overloading
The max method used above only applies to int type data. But what if you want to get the maximum value of two floating point types of data?
The solution is to create another method with the same name but different parameters, as shown in the following code:
public static double max(double num1, double num2) { if (num1 > num2) return num1; else return num2;}
If you pass an int parameter when calling the max method, the max method of the int parameter will be called;
If a double parameter is passed, the max method body of double type will be called, which is called method overloading;
That is, two methods of a class have the same name, but 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 based solely on modifiers or return types.
variable scope
The scope of a variable is the portion of the program that the variable can be referenced from.
Variables defined within a method are called local variables.
The scope of a local variable starts from the time it is declared and ends at the end of the block that contains it.
Local variables must be declared before they can be used.
The parameter scope of a method covers the entire method. The parameter is actually a local variable.
The variables declared in the initialization part of the for loop have scope throughout the loop.
But the scope of application of the variable declared in the loop body is from its declaration to the end of the loop body. It contains variable declarations as shown below:
You can declare a local variable with the same name multiple times within a method, in different non-nested blocks, but you cannot declare a local variable twice within a nested block.