参数在java程序中如何传递

来源:互联网 发布:2016淘宝客优惠券 编辑:程序博客网 时间:2024/04/25 19:35

 在Java 中,当你给方法传递一个简单类型时,它是按值传递的。因此,接收参数的子程序参数的改变不会影响到该方法之外。例如,看下面的程序:

  // Simple types are passed by value.

  class Test {

  void meth(int i,int j) { i *= 2;j /= 2;

  }

  }

  class CallByValue {

  public static void main(String args[]) {

  Test ob = new Test();

  int a = 15,b = 20;

  System.out.println("a and b before call: " +

  a + " " + b);

  ob.meth(a,b);

  System.out.println("a and b after call: " +

  a + " " + b);

  }

  }

  该程序的输出如下所示:

  a and b before call: 15 20

  a and b after call: 15 20

  可以看出,在meth( ) 内部发生的操作不影响调用中a和b的值。它们的值没在本例中没有变为30和10。

 

 

 

当你给方法传递一个对象时,这种情形就会发生戏剧性的变化,因为对象是通过引用传递的。记住,当你创建一个类类型的变量时,你仅仅创建了一个类的引用。因此,当你将这个引用传递给一个方法时,接收它的参数将会指向该参数指向的同一个对象。这有力地证明了对象是通过引用调用传递给方法的。该方法中对象的改变确实影响了作为参数的对象。例如,考虑下面的程序:

  // Objects are passed by reference.

  class Test { int a,b;

  Test(int i,int j) {a = i;b = j;

  }

  // pass an object

  void meth(Test o) {

  o.a *= 2;

  o.b /= 2;

  }

  }

  class CallByRef {public static void main(String args[]) { Test ob = new Test(15,20);

  System.out.println("ob.a and ob.b before call: " +

  ob.a + " " + ob.b);

  ob.meth(ob);

  System.out.println("ob.a and ob.b after call: " +

  ob.a + " " + ob.b);

  }

  }

  该程序产生下面的输出:

  ob.a and ob.b before call: 15 20

  ob.a and ob.b after call: 30 10

  正如你所看到的,在这个例子中,在meth ( ) 中的操作影响了作为参数的对象。

  有趣的一点是,当一个对象引用被传递给方法时,引用本身使用按值调用被传递。

原创粉丝点击