java 获取另一个类中方法的值,如何增加一个类整数从另一个方法引用java中的值...

package myintergertest;

/**

*

* @author Engineering

*/

public class Main {

/**

* @param args the command line arguments

*/

public static void main(String[] args) {

//this one does not increment

Integer n = new Integer(0);

System.out.println("n=" + n);

Increment(n);

System.out.println("n=" + n);

Increment(n);

System.out.println("n=" + n);

Increment(n);

System.out.println("n=" + n);

Increment(n);

//this one will increment

MyIntegerObj myInt = new MyIntegerObj(1);

Increment(myInt);

System.out.println("myint = " + myInt.get());

Increment(myInt);

System.out.println("myint = " + myInt.get());

Increment(myInt);

System.out.println("myint = " + myInt.get());

}

public static void Increment(Integer n) {

//NO. this doesn't work because a new reference is being assigned

//and references are passed by value in java

n++;

}

public static void Increment(MyIntegerObj n) {

//this works because we're still operating on the same object

//no new reference was assigned to n here.

n.plusplus(); //I didn't know how to implement a ++ operator...

}

}

所有这些的结果是n = 0。整数n是一个对象,因此通过引用传递,所以为什么增量反映在调用方法(main)中?我预计输出为n = 0 n = 1 n = 2等…

更新:

注意我更新了上面的代码示例。如果我正确理解,Jon Skeet回答了为什么我的Int会增加,为什么没有n的问题。这是因为n在Increment方法中得到了一个新的引用。但是,由于MyInt调用了一个成员函数,所以我没有得到新的引用。

听起来我听得懂吗?

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值