Home  >  Article  >  Java  >  Introduction to method overloading and variable scope in Java

Introduction to method overloading and variable scope in Java

高洛峰
高洛峰Original
2017-01-19 14:38:331680browse

Overloading of methods
The max method used above is only applicable 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, Then the max method of the int type parameter will be called;
If the double type parameter is passed, the double type max method body will be called, which is called method overloading;
It means 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 part of the program where the variable can be referenced.
Variables defined within a method are called local variables.
The scope of a local variable starts from the declaration and ends at the end of the block containing it.
Local variables must be declared before they can be used.
The parameter range of the method covers the entire method. The parameter is actually a local variable.
The variables declared in the initialization part of the for loop have their scope within the entire 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:

Introduction to method overloading and variable scope in Java

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

For more articles related to Java’s method overloading and introduction to variable scope, please pay attention to 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