• java中的值传递和引用传递


    传值---传递基本数据类型参数
    public    class           PassValue{
        static void exchange(int a, int b){//静态方法,交换a,b的值
            int temp;
            temp = a;
            a = b;
            b = temp;
        }
        public static void main(String[] args){
           int i = 10;
           int j = 100;
           System.out.println("before call: " + "i=" + i + "\t" + "j = " + j);//调用前
            exchange(i, j);                                                                    //值传递,main方法只能调用静态方法
            System.out.println("after call: " + "i=" + i + "\t" + "j = " + j);//调用后
        }
    }
    运行结果:
            before call: i = 10        j = 100
            after    call: i = 10        j = 100
    说明:调用exchange(i, j)时,实际参数i,j分别把值传递给相应的形式参数a,b,在执行方法exchange()时,形式参数a,b的值的改变不影响实际参数i和j的值,i和j的值在调用前后并没改变。
    引用传递---对象作为参数
    class Book{
        String name;
        private folat price;
        Book(String n,    float ){                //构造方法
            name = n;
            price = p;
        }
        static  void  change(Book a_book,    String n,    float p){    //静态方法,对象作为参数
                a_book.name = n;
                a_book.price = p;
        }
        public void output(){        //实例方法,输出对象信息
            System.out.println("name: " + name + "\t" + "price: " + price);
        }
    }
     public class PassAddr{
        public static void main(String [] args){
            Book b = new Book("java2",    32.5f);
            System.out.print("before call:\t");        //调用前
            b.output();
            b.change(b,    "c++",    45.5f);            //引用传递,传递对象b的引用,修改对象b的值
            System.out.print("after call:\t");            //调用后
            b.output();
        }
    }
    运行结果:
            before    call:    name:java2        price:32.5
            after       call:    name:c++          price:45.5
    说明:调用change(b,"c++",45.5f)时,对象b作为实际参数,把引用传递给相应的形式参数a_book,实际上a_book也指向同一个对象,即该对象有两个引用名:b和a_book。在执行方法change()时,对形式参数a_book操作就是对实际参数b的操作。

  • 相关阅读:
    c# 自定義事件
    c# 判斷事件中鼠標的左右按鍵
    I swear(我發誓)
    SQL Server实用操作小技巧集合
    富人和穷人的经典差异
    Mssql入门语句
    c# 匿名方法學習
    SOS: Autodesk MapGuide Studio Preview can not display "Feature Label" with Chinese text on the platform of MapGuide Open Source
    MapGuide open source开发心得二: 资源
    moblie development based on .net compact framework2 solution:activeX
  • 原文地址:https://www.cnblogs.com/xuerongli/p/2945679.html
Copyright © 2020-2023  润新知