Methods for Java, method overloading of understanding

A method

1. What is the method of
method is a code snippet, it cited elsewhere, which is similar to the C language "function."
2. The method of naming
must be a letter, underscore or '$' symbol at the beginning; may include numbers, but can not start with him.
3. The method of basic grammar

// 方法定义
public static 方法返回值 方法名称([参数类型 形参 ...]){
方法体代码;
 [return 返回值];
}
// 方法调用
返回值变量 = 方法名称(实参...);

NOTE: The parameter called the "parameter" is defined method, the parameter referred to as "arguments" when the method is called.
4. Examples of
code for adding two numbers

public static void main(String[] args) {
int a = 10;
int b = 20;
        
        // 方法的调用
int ret = add(a, b);
System.out.println("ret = " + ret);
 }
    // 方法的定义
public static int add(int x, int y) {
return x + y;
 }
}

Second, the method overloading

1. What is the method overloading
the same method name, offer different versions of the implementation, called method overloading.
2.
to add a similar method, if there are two floating point numbers are added, or three numbers together, will be used herein overloaded methods, specifically implemented as follows:

 class Test { 
         public static void main(String[] args) { 
                             int a = 10; 
                             int b = 20; 
                             int ret = add(a, b); 
                             System.out.println("ret = " + ret); 

                             double a2 = 10.5; 
                             double b2 = 20.5; 
                             double ret2 = add(a2, b2); 
                             System.out.println("ret2 = " + ret2); 

                             double a3 = 10.5; 
                             double b3 = 10.5; 
                             double c3 = 20.5; 
                             double ret3 = add(a3, b3, c3); 
                             System.out.println("ret3 = " + ret3); 
             }
                 //两个整数相加
                 public static int add(int x, int y) { 
                         return x + y; 
             } 
                 //两个浮点数相加 
                 public static double add(double x, double y) { 
                            return x + y; 
             } 
                //三个浮点数相加
                  public static double add(double x, double y, double z) { 
                            return x + y + z; 
         } 
}

3. overloaded rules
for the same class:
● A method for the same name
● different parameters of the method (the number of parameters or parameter types)
return type method does not affect the reload ●
Third, recursive method

Guess you like

Origin blog.51cto.com/14298563/2447441