在Java编程中,将对象或者数组作为方法的入参传递,可以在方法中修改对象或者数组的值,回传给调用者,这样入参又承担了出参的角色。
代码示例:
定义一个类:
package com.thb;
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
}
定义一个主类:
package com.thb;
public class Test2 {
public static void main(String[] args) {
Test2 test = new Test2();
// 类
Point point = new Point(1, 3);
System.out.println("before invoking changePoint(Point point): " + point);
System.out.println("before invoking changePoint(Point point), point.x = " + point.getX());
System.out.println("before invoking changePoint(Point point), point.y = " + point.getY());
// 用对象作为函数的参数
test.changePoint(point);
System.out.println("after invoking changePoint(Point point), point.x = " + point.getX());
System.out.println("after invoking changePoint(Point point), point.y = " + point.getY());
System.out.println("----------------------------------------------");
// 数组
int[] chs= new int[2];
// 用数组作为参数
test.changeArray(chs);
System.out.println("after invoking changeArray(int[] chs) method:");
for (int i = 0; i < chs.length; i++) {
System.out.println("chs[" + i + "] = " + chs[i]);
}
}
public void changePoint(Point point) {
System.out.println(point);
point.setX(point.getX() + 2);
point.setY(point.getY() + 2);
}
public void changeArray(int[] chs) {
for (int i = 0; i < chs.length; i++) {
chs[i] = i + 5;
}
}
}
运行结果: