04 _ java object-oriented data transfer

No java pointer (so not passed by reference), the method all parameters are passed by value , passing a copy of the value.

1. The basic data transfer types

The actual parameter values ​​to pass its corresponding formal parameters, a method of changing the form of the execution parameter values ​​do not affect the value of the actual parameter.

[Example] swap values ​​of the variables

public class ObjectDemo {
	public static void main(String[] args) {
		int a = 10, b = 20;
		// 输出:交换之前:a:10 b: 20
		System.out.println("交换之前:a:" + a + " b: " + b);
		// 交换变量a和b的值
		swap(a, b);
		// 输出:交换之后:a:10 b: 20
		System.out.println("交换之后:a:" + a + " b: " + b);
	}
	// 交换两个变量的值
	public static void swap(int num1, int num2) {
		int temp = num1;
		num1 = num2;
		num2 = temp;
	}
}

Summary: method call, the value of the argument is copied into the parameters, exchanged in the share function is copied values, rather than real parameter data itself. Therefore, internal method to modify the parameter value, the method argument will not follow the external parameter changed together.

2. The reference data types passed

The actual parameter values ​​to pass its corresponding formal parameters, a method of changing the form of the execution parameters directly affect the actual parameters.

[Example] swap values ​​of the variables

// 坐标类
class Point {
	// 成员变量
	double x;
	double y;
	// 构造方法
	public Point(double x, double y) {
		this.x = x;
		this.y = y;
	}
}
// 测试类
public class PointTest {
	public static void main(String[] args) {
		// 创建一个坐标对象
		Point point = new Point(10.0, 20.0);
		// 输出:交换之前:x: 10.0 y:20.0
		System.out.println("交换之前:x: " + point.x + " y:" + point.y);
		// 交换point中x和y的值
		swap(point);
		// 输出:交换之后:x: 20.0 y:10.0
		System.out.println("交换之后:x: " + point.x + " y:" + point.y);
	}
	// 交换坐标对象中x和y的值
	public static void swap(Point point) {
		double temp = point.x;
		point.x = point.y;
		point.y = temp;
	}
}

Method call, arguments are passed to the address stored in the corresponding process parameter, and parameter arguments therefore point to an address of the same stack, in the process of execution, the operation of the parameter is actually on arguments operation. Therefore, a method of operating parameters form, the external process will also change with the argument.

ps: For the latest free documentation and instructional videos, please add QQ group (627,407,545) receive.

Published 33 original articles · won praise 0 · Views 307

Guess you like

Origin blog.csdn.net/zhoujunfeng121/article/details/104581589