Java method overload and variable scope introduction _java

Source: Internet
Author: User

Overload of the method
the Max method used above applies only to int-type data. But what if you want to get the maximum value for two floating-point types of data?
The workaround is to create another method that has 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 you call the Max method, the Max method of the int parameter is called;
If the thing is passed the double parameter, the Max method of the double type is called, which is called the method overload;
This means that two methods of a class have the same name, but have different argument lists.
The Java compiler determines which method should be invoked based on the method signature.
Method overloading makes the program clearer and easier to read. Methods that perform closely related tasks should use the same name.
Overloaded methods must have a different parameter list. You cannot overload a method simply by modifiers or by the difference of the return type.
variable Scope
the scope of a variable is the part of the program that the variable can be referenced.
A variable defined within a method is called a local variable.
The scope of a local variable starts at the declaration until the block containing it ends.
Local variables must be declared before they can be used.
The parameter range of the method covers the entire method. The argument is actually a local variable.
The initialization part of the For loop declares a variable whose scope is scoped throughout the loop.
But a variable declared within a loop body is scoped to the end of its declaration to the loop body. It contains the variable declaration as follows:

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.