方法参数的传递

当对象作为参数时,参数的值是该对象的引用,这时对象的内容可以在方法中改变,但是对象的引用不会改变。

public class PassTest{
    float ptValue;
    
    //参数类型是基本类型
    public void changeInt(int value){
        value = 55 ; 
    }
    
    //参数类型是引用型,并且方法中改了变参数的值
    public void changeStr(String value){
        value = new String("different"); 
    }
    
    //参数类型是引用型,并且方法中改了变参数所指向对象的成员变量值
    public void changeObjValue( PassTest ref){
        ref.ptValue = 99.0f; 
    }
    
    public static void  main(String args[ ] ){
        String str;
        int val;
        
        PassTest pt= new PassTest( );  
        val = 11;
        pt.changeInt(val);
        System.out.println("Int value is: " +val);


        str = new String("Hello");
        pt.changeStr(str);
        System.out.println("Str value is: " +str);
        
      
        pt.ptValue = 101.0f ;
        pt.changeObjValue(pt);
        System.out.println("Pt value is: " +pt.ptValue);
    }
}

文字解释在代码中

图解:

 

posted @ 2018-03-29 19:51  风雨长安  阅读(338)  评论(0编辑  收藏  举报
博客