User-Defined Methods (Part 1) 用户自定义方法(上)
Learning Objectives 学习目标
- Decompose complex operations by writing modular user-defined methods.
- Pass argument parameters by value and design return statements.
- Identify scope variables boundaries and local identifier visibility.
- 通过编写模块化的用户自定义方法来分解复杂操作。
- 按值传递参数并设计返回语句。
- 识别作用域变量边界和局部标识符可见性。
2 · Method Declaration Structure
A method is a reusable block of code designed to perform a specific task. Declaring methods enforces modular design, making programs cleaner and reducing duplicates. Java method headers contain: 方法是为执行特定任务而设计的可重用代码块。声明方法可以强制执行模块化设计,使程序更清晰并减少重复代码。Java 方法头包含:
modifier returnType methodName(parameterList) {{
// method body
}}
Example: public static double calculateTax(double amount). Here, public static are modifiers, double is the return type, calculateTax is the method name, and double amount is a formal parameter.
示例:public static double calculateTax(double amount)。这里,public static 是修饰符,double 是返回类型,calculateTax 是方法名称,而 double amount 是形参。
3 · Parameters & Return Statements
Java passes parameters to methods by value, meaning the method receives a copy of the argument values. A method can output values back to callers using the return keyword:
Java 按值传递参数给方法,这意味着方法收到的是实参值的副本。方法可以使用 return 关键字将值输出返回给调用者:
public static int multiply(int a, int b) {{ return a * b; // returns value product to caller }}
If a method does not return a value, its return type must be declared as void.
如果方法不返回值,则必须将其返回类型声明为 void。
4 · Local Variable Scope
A variable declared inside a method is called a local variable. Its scope is bounded by the enclosing curly braces {{ ... }}. It cannot be accessed or modified from outside the method:
在方法内声明的变量称为局部变量。它的作用域受到闭合大括号 {{ ... }} 的限制。不能从方法外部访问或修改它:
| Property属性 | Local Variable局部变量 | Method Parameter方法参数 |
|---|---|---|
| Declaration Location声明位置 | Inside method body | Inside method header parenthesis |
| Initial Value Source初始值来源 | Explicit assignment inside method | Copied from argument passed during call |
| Visibility Limits可见性限制 | From declaration to end of method | Accessible throughout entire method body |
Applied Case Study: Modular Calculations Engine应用案例研究:模块化计算引擎
Company: Kompas Calculator Engine.
We encapsulate calculation logic into modular static methods. The main routine prompts user, passes arguments, and prints formatted output values.
公司: Kompas Calculator Engine。
我们将计算逻辑封装到模块化静态方法中。主方法提示用户输入、传递参数,并打印格式化的输出值。
Calculator Engine Source Code计算引擎程序源代码
import java.util.Scanner; public class CalcEngine {{ // Method to calculate subtotal public static double calculateSubtotal(double price, int qty) {{ return price * qty; }} // Method to calculate tax public static double calculateTax(double subtotal, double taxRate) {{ return subtotal * taxRate; }} public static void main(String[] args) {{ Scanner input = new Scanner(System.in); System.out.print("Enter item price: RM "); double price = input.nextDouble(); System.out.print("Enter item quantity: "); int qty = input.nextInt(); double sub = calculateSubtotal(price, qty); double tax = calculateTax(sub, 0.06); // 6% tax rate double total = sub + tax; System.out.printf("Subtotal: RM %.2f%n", sub); System.out.printf("Tax (6%%): RM %.2f%n", tax); System.out.printf("Grand Total: RM %.2f%n", total); input.close(); }} }}
💡 Hint / 提示
Notice variables names in main (e.g. price, qty) match arguments, but parameter names (e.g. price, qty inside calculateSubtotal) copy these values into separate memory addresses.注意 main 中的变量名(例如 price、qty)与实参匹配,但形参名(例如 calculateSubtotal 中的 price、qty)会将这些值复制到独立的内存地址中。
✅ Show Expected Console Flow / 显示预期控制台运行
Enter item price: RM 20.00 Enter item quantity: 5 Subtotal: RM 100.00 Tax (6%): RM 6.00 Grand Total: RM 106.00
Check Your Understanding自我检测
Q1. What return type is used when a method does not return any value?当方法不返回任何值时,使用什么返回类型?
Q2. In Java, how are primitive arguments passed to methods?在 Java 中,基本类型实参是如何传递给方法的?
Q3. Where are variables declared inside a user-defined method visible?在用户自定义方法内部声明的变量在哪里是可见的?