Java study notes (thirteen): member method considerations and formal parameter list

Table of contents

Member method notes:

Formal parameter list:

method body


Member method notes:

1. The types of actual parameters and formal parameters must be consistent or compatible, and the number and order must be consistent

2. When calling a method with parameters, you must pass in parameters of the same type or compatible types corresponding to the parameter list

public class Method {

    public static void main(String[] args) {
    AA a = new AA();
    byte b1 = 1;
	byte b2 = 2;
	a.people(b1, b2);//√。byte可以传给people里面的int
 	//a.people(1.1, 1.2);//错。double高精度无法给到people里面低精度int
    a.people2("java", 100); //√
    //a.peolpe2(100, "java"); // 错的。实际参数和形式参数顺序不对

    }
}
class Test{

    public int[] people(int n1, int n2) {

     }
    public void people2(String str, int n){
    
    }
}

3. Methods cannot be defined nested

public void people() {
    //public void people2() {//错的
//方法中不能再定义一个方法,
//一个类中可以定义多个方法,但一个方法内不能定义多个方法。
//所以这条语句是错误的。
    }
}

4. A method has at most one return value

public int[] getPeople(int n1, int n2) {
int[] peo = new int[2]; 
peo[0] = n1 + n2;
peo[1] = n1 - n2; 
return peo;
}

5. If the method requires a return data type, the last execution statement in the method body must be the return value ; and the return value type must be consistent or compatible with the return value type

public double method() {
double d1 = 1.1 * 3; 
int n = 100;
return n; // 根据基本数据类型,int可以传给double,而double不能给int,如果返回类型为int就会报错

}

If the method is void, there may be no return statement in the method body, or just return;

Formal parameter list:

1. A method can have 0 parameters or multiple parameters, separated by commas .

eg:getPeople(int n,double x)

2. The parameter type can be any type, including basic type or reference type.

eg:printArray(int[][] map)

3. When calling a method with parameters, parameters of the same type or compatible types must be passed in corresponding to the parameter list . (Already demonstrated above)

4. The parameters in method definition are called formal parameters, referred to as formal parameters; the incoming parameters in method calling are called actual parameters, referred to as actual parameters. The types of actual parameters and formal parameters must be consistent or compatible, and the number and order must be consistent . (Already demonstrated above)

Method body:

The specific statement to complete the function is written in the method body, which can be input, output, variable, operation, loop, method call, branch, etc., but the method cannot be defined again . Methods cannot be defined nested! (Already demonstrated above)

Guess you like

Origin blog.csdn.net/long_0901/article/details/124533080