java函数参数传值之我见

类别:Java 点击:0 评论:0 推荐:

在一些群里总是有人问java函数传的到底是什么,这阵子有时间了,思考了一下,找了个演示小程序
又按自己的理解画了个图,如果有人光顾我的blog的话,可以讨论一下

class Obj
{
     String str = "init value";
     public String toString() //overiding重写了toString()方法,可以被显式或隐式调用
     {
          return str+"+Haha-yang";
     }
}

public class ObjRef
{
     Obj aObj = new Obj();
 
     int aInt = 11;
 
     public void changeObj(Obj inObj)
     {
          inObj.str = "changed value"; //可以改变传递进入对象的属性值
     }
 
     public void changePri(int inInt)
     {
          inInt = 22;
     }
 
     public static void main(String[] args)
     {
          ObjRef oRef = new ObjRef();
          System.out.println("1  Before call changeObj() method: " + oRef.aObj);//在这里,oRef.aObj自动调用了Obj类的toString()方法(隐式调用)
          System.out.println("2  Before call changeObj() method: " + oRef.aObj.toString());//在这里,oRef.aObj调用了Obj类的toString()方法(显式调用)
  
          System.out.println("3  Before call changeObj() method: " + oRef.aObj.str);
  
          oRef.changeObj(oRef.aObj);
          System.out.println("4  After call changeObj() method: " + oRef.aObj);//oRef.aObj隐式调用了父类的toString()方法
          System.out.println("4b After call changeObj() method: " + oRef.aObj.toString());//oRef.aObj显式调用了父类的toString()方法
  
          System.out.println("3b Before call changeObj() method: " + oRef.aObj.str);
  
          System.out.println("==================Print Primtive=================");
          System.out.println("5  Before call changePri() method: " + oRef.aInt);
  
          oRef.changePri(oRef.aInt);
          System.out.println("6  After call changePri() method: " + oRef.aInt);

     }
}

输出:
C:\123>java ObjRef
1  Before call changeObj() method: init value+Hahayang
2  Before call changeObj() method: init value+Hahayang
3  Before call changeObj() method: init value
4  After call changeObj() method: changed value+Hahayang
4b After call changeObj() method: changed value+Hahayang
3b Before call changeObj() method: changed value
==================Print Primtive=================
5  Before call changePri() method: 11
6  After call changePri() method: 11

本文地址:http://com.8s8s.com/it/it11339.htm