引用作为参数传递时容易搞错的两个例子

//例子1:

class Value
{
public int i = 15;
}

public class PassRefrence
{
public static void main(String argv[])
{
PassRefrence t = new PassRefrence();
t.first();
}

public void first()
{
int i = 5;
Value v = new Value();
v.i = 25;
second(v, i);
System.out.println(v.i);

}

public void second(Value v, int i)
{
i = 0;
v.i = 20;
Value val = new Value();
v = val;
System.out.println(v.i + " " + i);

}
}

输出结果为:
15 0
20


输出结果为:
15 0
20

参数传到一个方法中后,在方法中对参数值的改变不会影响原来的值,对primitive和object refrence 都一样。对引用来说就是,在方法中又new 了一个对象并把该对象的引用赋给传递进来的参数,这样并不影响方法外的引用所指向的地址。

另外:

//例子2:

class Test
{
public static void main(String [] args)
{
Base b = new Subclass();
System.out.println(b.x);
System.out.println(b.method());
}
}

class Base
{
int x = 2;
int method()
{
return x;
}
}

class Subclass extends Base
{
int x = 3;
int method()
{
return x;
}
}

输出结果为:

2

3

The rule for accessing methods and variables in a class hierarchy is as follows:
-the object reference is used when accessing variables (so the value of b.x is therefore 2).
-the underlying object is used when accessing methods (so the method called is actually the method defined in Subclass, and in Subclass, x = 3).

用父类或接口调用子类的覆盖方法时,根据动态绑定确定调用哪个子类的方法,但调用成员变量时,直接访问父类或接口的成员变量

输出结果为:

2

3
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值