java对象、数组作为函数的入参和出参

在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;
		}
	}
}

运行结果:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值