Java编程-谈谈JAVA中的调用方式

分类: J2SE   出处:iocblog整理  更新时间:2008-12-15   添加到收藏  


  很多书籍都说java支持传引用调用的方式,类似于c++中的person &a引用调用,而近来编程遇到一系列问题让我对此产生了怀疑,于是将这些方法一一列出,我们来一起看看java中的调用方式:
  
  看下面的程序:
  
  class person {
  
  private string name;//姓名
  
  private string sex;//性别
  
  public person(string x, string y) {
  this.name = x;
  this.sex = y;
  }
  
  public void setstatus(string x, string y) {
  this.name = x;
  this.sex = y;
  
  }
  
  public string tostring() {
  
  return name + sex;
  
  }
  
  // -----交换普通对象-----
  public static void changeref(person tmpx, person tmpy) {
  //交换tmpx和tmpy对象
  person swapref = tmpx;
  tmpx = tmpy;
  tmpy = swapref;
  //    system.out.println("在方法中交换的结果: refa =" + tmpx.tostring());
  //    system.out.println("在方法中交换的结果: refb =" + tmpy.tostring());
  }
  
  // ----- 交换数组对象-----
  public static void changearrayref(person[] x, person[] y) {
  
  //交换数组对象
  person swaparrayref = x[x.length-1];
  x[x.length-1] =y[x.length-1];
  y[x.length-1] = swaparrayref;
  
  }
  
  //-----交换数组-----
  public static void changearray(int[] x,int[] y) {
  
  int[] tmp =x;
  x = y;
  y = tmp;
  
  }
  
  }
  
  public class demo {
  
  public static void main(string[] args) {
  
  //-------建立并构造两个对象---------
  person refa = new person("张三", "男");
  person refb = new person("李四", "男");
  
  //交换refa对象和refb对象
  person.changeref(refa, refb);
  //从交换结果中看出,实际对象并未交换
  system.out.println("在主函数中交换的结果 refa = " + refa.tostring());
  system.out.println("在主函数中交换的结果 refb = " + refb.tostring());
  
  //-------建立两个对象数组----------
  person[] arraya = new person[1];
  person[] arrayb = new person[1];
  
  //分别构造数组对象
  arraya[0] = new person("王五","男");
  arrayb[0] = new person("赵六","男");
  
  /*数组对象为null时,不能设置其值,必须先构造它(即调用构造函数),再用其它方法设置其值
  */
  

[1] [2] 下一页


Tag: Java编程



文章整理:iocblog
版权申明:本站文章均来自网络,如有侵权,请联系我们,我们收到后立即删除,谢谢!
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有。