ITeye博客

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

sunmiracle · 2010-11-27 21:48 · 编程语言 · Markdown

//例子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)

暂无评论。

评论功能维护中,当前仅展示历史评论。