Method in Java--方法

In this session, we learn how to define methods to solve complex problems.

本章节我们学习使用方法来解决复杂问题。

Opening Problem

问题引入

Suppose you need to find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

如果你需要分别求出1到10的和,20到30的和,35到45的和。

You may write the code as shown following:

我们可以像下面这样分开写。

Slide 5:
You may have observed that computing these sums from 1 to 10, from 20 to 30, and from 35 to 45 are very similar, except that the starting and ending integers are different. Wouldn’t it be nice if we could write the common code once and reuse it? We can do so by defining a method and invoking it.

Slide 6:
The code in the previous slide can be simplified as shown in this slide.

The code shown in this slide defines the method named sum with two parameters i1 and i2. The statements in the main method invoke sum(1, 10) to compute the sum from 1 to 10, sum(20, 30) to compute the sum from 20 to 30, and sum(35, 45) to compute the sum from 35 to 45. A method is a collection of statements grouped together to perform an operation. In earlier sessions you have used predefined methods such as System.out.println, System.exit, Math.pow, and Math.random. These methods are defined in the Java library. In this session, you will learn how to define your own methods to solve complex problems.

Slide 7:
A method definition consists of method name, parameters, return value type, and body. The syntax for defining a method is shown in this slide.

Slide 8:
Let’s look at a method defined to find the larger between two integers. This method, named max, has two int parameters, num1 and num2, the larger of which is returned by the method

Slide 9:
The method header specifies the modifiers, return value type, method name, and parameters of the method.

Slide 10:
A method may return a value. The returnValueType is the data type of the value the method returns. Some methods perform desired operations without returning a value. In this case, the returnValueType is the keyword void. For example, the returnValueType is void in the main method, as well as in System.exit, and System.out.println. If a method returns a value, it is called a value-returning method; otherwise, it is called a void method.

Slide 11:
The variables defined in the method header are known as formal parameters or simply parameters. A parameter is like a placeholder: when a method is invoked, you pass a value to the parameter. This value is referred to as an actual parameter or argument. The parameter list refers to the method’s type, order, and the number of parameters.
 
Slide 12:
When a method is invoked, you pass a value to the parameter. This value is referred to as an actual parameter or argument.

Slide 13
The parameter list refers to the method’s type, order, and the number of parameters. The method name and the parameter list together constitute the method signature. Parameters are optional; that is, a method may contain no parameters. For example, the Math.random() method has no parameters.
The method body contains a collection of statements that implement the method.

Slide 14
In a method definition, you define what the method is to do. To execute the method, you have to call or invoke it. The program that calls the function is called a caller. There are two ways to call a method, depending on whether the method returns a value or not.
If a method returns a value, a call to the method is usually treated as a value. For example, int larger = max(3, 4); calls max(3, 4) and assigns the result of the method to the variable larger. Another example of a call that is treated as a value is System.out.println(max(3, 4)); which prints the return value of the method call max(3, 4).
If a method returns void, a call to the method must be a statement. For example, the method println returns void. The following call is a statement: System.out.println("Welcome to Java!");
When a program calls a method, program control is transferred to the called method. A called method returns control to the caller when its return statement is executed or when its method-ending closing brace is reached

Slide 15
This program contains the main method and the max method. The main method is just like any other method, except that it is invoked by the JVM to start the program.
The statements in main may invoke other methods that are defined in the class that contains the main method or in other classes. In this example, the main method invokes max(i, j), which is defined in the same class with the main method.
When the max method is invoked, variable i’s value 5 is passed to num1 and variable j’s value 2 is passed to num2 in the max method. The flow of control transfers to the max method and the max method is executed. When the return statement in the max method is executed, the max method returns the control to its caller (in this case, the caller is the main method).
The next slides show how the max method is called from the main method.

Slide 26:
Each time a method is invoked, the system creates an activation record that stores parameters and variables for the method and places the activation record in an area of memory known as a call stack. A call stack is also known as an execution stack, runtime stack, or machine stack and it is often shortened to just “the stack.”
When a method calls another method, the caller’s activation record is kept intact and a new activation record is created for the new method called. When a method finishes its work and returns to its caller, its activation record is removed from the call stack.
A call stack stores the activation records in a last-in, first-out fashion: The activation record for the method that is invoked last is removed first from the stack. For example, suppose method m1 calls method m2, and m2 calls method m3. The runtime system pushes m1’s activation record into the stack, then m2’s, and then m3’s. After m3 is finished, its activation record is removed from the stack. After m2 is finished, its activation record is removed from the stack. After m1 is finished, its activation record is removed from the stack.

Slide 27:
Understanding call stacks helps you to comprehend how methods are invoked. The variables defined in the main method in are i, j, and k. The variables defined in the max method are num1, num2, and result. The variables num1 and num2 are defined in the method signature and are parameters of the max method. Their
 
values are passed through method invocation. This slide illustrates the activation records for method calls in the stack.
The next slides trace the call stack and illustrate how the main and max methods are executed and the system creates activation records for them.

Slide 38:
A void method does not return a value. The method performs some actions. A call to a void method must be a statement.
A return statement is not needed for a void method, but it can be used for terminating the method and returning to the method’s caller. The syntax is simply return;
This is not often done, but sometimes it is useful for circumventing the normal flow of control in a void method.

Slide 39
The power of a method is its ability to work with parameters. You can use println to print any string, and max to find the maximum of any two int values. When calling a method, you need to provide arguments, which must be given in the same order as their respective parameters in the method signature. This is known as parameter order association. For example, the method shown in this slide prints a message n times.
You can use nPrintln("Hello", 3) to print Hello three times. The nPrintln("Hello", 3) statement passes the actual string parameter Hello to the parameter message, passes 3 to n, and prints Hello three times. However, the statement nPrintln(3, "Hello") would be wrong. The data type of 3 does not match the data type for the first parameter, message, nor does the second argument, Hello, match the second parameter, n.
The arguments must match the parameters in order, number, and compatible type, as defined in the method signature. Compatible type means you can pass an argument to a parameter without explicit casting, such as passing an int value argument to a double value parameter.

Slide 40
When you invoke a method with an argument, the value of the argument is passed to the parameter. This is referred to as pass-by-value. If the argument is a variable rather than a literal value, the value of the variable is passed to the parameter. The variable is not affected, regardless of the changes made to the parameter inside the method.

Slide 41:
This slide shows the stack call for the main and swap methods. Before the swap method is invoked, num1 is 1 and num2 is 2. After the swap method is invoked, num1 is still 1 and num2 is still 2. Their values have not been swapped. As you can see in this slide, the values of the arguments num1 and num2 are passed to n1 and n2, but n1 and n2 have their own memory locations independent of num1 and num2. Therefore, changes in n1 and n2 do not affect the contents of num1 and num2.

Overloading

方法的重载

Overloading methods enable you to define the methods with the same name as long as their parameter lists are different.

Slide 43:
The max method used earlier works only with the int data type. But what if you need to determine which of the two floating-point numbers has the maximum value? The solution is to create another method with the same name but different parameters, as shown in this slide.

If you call max with int parameters, the max method that expects int parameters will be invoked; and if you call max with double parameters, the max method that expects double parameters will be invoked. This is referred to as method overloading; that is, two methods have the same name but
 
different parameter lists within one class. The Java compiler determines which method to use based on the method signature.
Overloading methods can make programs clearer and more readable. Methods that perform the same function with different types of parameters should be given the same name.
Overloaded methods must have different parameter lists. You cannot overload methods based on different modifiers or return types.

Slide 44:
Sometimes there are two or more possible matches for the invocation of a method, but the compiler cannot determine the most specific match. This is referred to as ambiguous invocation. Ambiguous invocation causes a compile error.

Slide 45
Consider the code shown in this slide. Both max(int, double) and max(double, int) are possible candidates to match max(1, 2). Because neither is more specific than the other, the invocation is ambiguous, resulting in a compile error.

Slide 46
A variable defined inside a method is referred to as a local variable. The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be declared and assigned a value before it can be used.
A parameter is actually a local variable. The scope of a method parameter covers the entire method.

Slide 47
You can declare a local variable with the same name multiple times in different non-nesting blocks in a method, but you cannot declare a local variable twice in nested blocks.

Slide 48
A variable declared in the initial-action part of a for-loop header has its scope in the entire loop. However, a variable declared inside a for-loop body has its scope limited in the loop body from its declaration to the end of the block that contains the variable.

Slide 49
This slide show that it is fine to declare i in two non-nested blocks but it is wrong to declare i in two nested blocks

Slide 50:
This slide show a method with local variables that runs fine with no errors.

Slide 51
This slide show a method with local variables that has compile errors.
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一只萌新兔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值