zoukankan      html  css  js  c++  java
  • java中函数传值与引用问题

    从C++转java,在使用函数传对象时,碰到一点问题,今天特意验证了一下:

    public class App 
    {
        public static void doubleTest(double d) {
            d=8.0;
            System.out.println( "[INNER doubleTest]double:"+d);
        }
        public static void DoubleTest(Double dd) {
            dd=8.0;
            System.out.println( "[INNER DoubleTest]Double:"+dd);
        }
        public static void ObjectTest(ObjectChange obj) {
            obj = new ObjectChange(5);
            System.out.println( "[INNER ObjectTest]Object:"+obj.getTT());
            obj.setTT(8);
            System.out.println( "[INNER ObjectTest]Object:"+obj.getTT());
        }
        public static void ObjectChangeTest(ObjectChange obj) {
            obj.setTT(8);
            System.out.println( "[INNER ObjectChangeTest]Object:"+obj.getTT());
            obj = new ObjectChange(5);
            System.out.println( "[INNER ObjectChangeTest]Object:"+obj.getTT());
            obj.setTT(6);
            System.out.println( "[INNER ObjectChangeTest]Object:"+obj.getTT());
        }
        
        public static void main( String[] args )
        {
            System.out.println( "Source:" );
            double d1=1;
            Double d2=2.0;
            ObjectChange obj1 = new ObjectChange(1);
            System.out.println( "double:"+d1+"    Double:"+d2 +"    Object:"+ obj1.getTT());        
    
            System.out.println( "After:" );
            doubleTest(d1);
            DoubleTest(d2);
            ObjectTest(obj1);
            System.out.println( "double:"+d1+"    Double:"+d2 +"    Object:"+ obj1.getTT());
            ObjectChangeTest(obj1);
            System.out.println( "Object:"+ obj1.getTT());
        }
    }

    程序输出结果:

    总结:

    obj在函数体内作为临时变量,可读取对象内容,采用“=”(赋值运算符)改变的是临时对象的内容,赋值后,再操作的也是临时对象的内容;

    只有在赋值前调用对象的成员方法(setTT())才能真正改变obj对象的内容;

  • 相关阅读:
    [转载]Axis2 and CXF的比较
    [转载]Axure RP 7.0下载地址及安装说明
    Eclipse配置总结
    201505大事记
    Gmail收不到邮件咋办?
    Mybatis-There is no getter for property named 'id' in 'class java.lang.String'
    EXTjs+SpringMVC+Mybatis实现照片的上传,下载,查看关键技术整理
    Ext如何Gird中如何显示时间类型的列?
    glibc
    圆形头像CircleImageView和Cardview使用
  • 原文地址:https://www.cnblogs.com/HandyLi/p/10338578.html
Copyright © 2011-2022 走看看