Java Tutorial/Class Definition/Method Parameters
Содержание
By Value or By Reference
- Primitive variables are passed by value.
- reference variables are passed by reference.
- When you pass a primitive variable, the JVM will copy the value of the passed-in variable to a new local variable.
- If you change the value of the local variable, the change will not affect the passed in primitive variable.
- If you pass a reference variable, the local variable will refer to the same object as the passed in reference variable.
- If you change the object referenced within your method, the change will also be reflected in the calling code.
Passing objects to methods
class Letter {
char c;
}
public class MainClass {
static void f(Letter y) {
y.c = "z";
}
public static void main(String[] args) {
Letter x = new Letter();
x.c = "a";
System.out.println("1: x.c: " + x.c);
f(x);
System.out.println("2: x.c: " + x.c);
}
}
1: x.c: a 2: x.c: z
Reference Passing Test
class Point {
public int x;
public int y;
}
public class MainClass {
public static void increment(int x) {
x++;
}
public static void reset(Point point) {
point.x = 0;
point.y = 0;
}
public static void main(String[] args) {
int a = 9;
increment(a);
System.out.println(a); // prints 9
Point p = new Point();
p.x = 400;
p.y = 600;
reset(p);
System.out.println(p.x); // prints 0
}
}
9 0
Use an array to pass a variable number of arguments to a method. This is the old-style approach to variable-length arguments.
class PassArray {
static void vaTest(int v[]) {
System.out.print("Number of args: " + v.length + " Contents: ");
for (int x : v)
System.out.print(x + " ");
System.out.println();
}
public static void main(String args[]) {
int n1[] = { 10 };
int n2[] = { 1, 2, 3 };
int n3[] = {};
vaTest(n1); // 1 arg
vaTest(n2); // 3 args
vaTest(n3); // no args
}
}