What is a way
- Java methods are collections of statements that perform a function together
- A method is an ordered combination of steps to solve a class of problems
- Methods are contained in classes or objects
- Methods are created in the program and referenced elsewhere
Method definition
- Java methods are similar to functions in other languages. They are snippets of code that perform a specific function. Typically, defining a method contains the following syntax:
- A method contains a method header and a method body. Here are all the parts of a method:
Modifiers: Modifiers, optional, tell the compiler how to call the method. Defines the access type for the method. Return value types: Methods may return values. ReturnValue Type is the data Type of the value returned by the method. Some methods perform the desired action but return no value. In this case, return Value Type is the keyword void method name: is the actual name of the method. The method name and parameter list together make up the method signature parameter type: the parameter is like a placeholder. When a method is called, the value is passed to the parameter. This value is called an argument or variable. The number list refers to the method’s parameter types, order, and number of parameters. Arguments are optional, and methods can contain no arguments. Formal parameters: Data used to receive external input when a method is called. Argument: The data actually passed to the method when the method is called method body: The method body contains concrete statements that define the function of the method.
Modifier return value type method name (parameter type parameter name){/ / the method body
returnThe return value.// End method +
}
Copy the code
The method call
- Call method: object name. Method name (argument list)
- Java supports two invocation methods, selected based on whether the method returns a value.
- A method call is usually treated as a value when a method returns a value. Such as int large = Max (30, 40);
- If the method returns void, the method call must be a statement. System.out.println(“Hello”);
Extension: Value passing (Java) and reference passing
- Value passing and reference passing in detail
Method overloading
- An overload is a function that has the same function name but different parameters in a class.
- Rules for method overloading: – Method names must be the same. – The parameter list must be different in number, type, or sequence. – Methods can have the same or different return types – simply having different return types is not enough to be a method overload.
- Implementation theory: if the method name is the same, the compiler will match the method one by one according to the number of parameters, parameter type, etc., to select a pair
If the match fails, the compiler reports an error.