不同类型的方法传递
创始人
2025-01-09 07:30:15
0

在Java中,有多种不同的方法可以进行参数传递。下面是一些常见的方法传递的示例代码:

  1. 值传递:

    public static void main(String[] args) {
        int num = 5;
        System.out.println("Before calling method: " + num);
        changeValue(num);
        System.out.println("After calling method: " + num);
    }
    
    public static void changeValue(int value) {
        value = 10;
        System.out.println("Inside method: " + value);
    }
    

    输出:

    Before calling method: 5
    Inside method: 10
    After calling method: 5
    

    在值传递中,参数的值被复制到方法中,对参数的修改不会影响原始值。

  2. 引用传递:

    public static void main(String[] args) {
        int[] array = {1, 2, 3};
        System.out.println("Before calling method: " + Arrays.toString(array));
        changeArray(array);
        System.out.println("After calling method: " + Arrays.toString(array));
    }
    
    public static void changeArray(int[] arr) {
        arr[0] = 10;
        System.out.println("Inside method: " + Arrays.toString(arr));
    }
    

    输出:

    Before calling method: [1, 2, 3]
    Inside method: [10, 2, 3]
    After calling method: [10, 2, 3]
    

    在引用传递中,参数的引用被传递到方法中,对参数的修改会影响原始值。

  3. 对象传递:

    public class MyClass {
        private int value;
        
        public MyClass(int value) {
            this.value = value;
        }
        
        public int getValue() {
            return value;
        }
        
        public void setValue(int value) {
            this.value = value;
        }
    }
    
    public static void main(String[] args) {
        MyClass obj = new MyClass(5);
        System.out.println("Before calling method: " + obj.getValue());
        changeObject(obj);
        System.out.println("After calling method: " + obj.getValue());
    }
    
    public static void changeObject(MyClass obj) {
        obj.setValue(10);
        System.out.println("Inside method: " + obj.getValue());
    }
    

    输出:

    Before calling method: 5
    Inside method: 10
    After calling method: 10
    

    在对象传递中,参数的引用被传递到方法中,对参数的修改会影响原始对象的状态。

相关内容

热门资讯

揭秘!pokermaster脚... 揭秘!pokermaster脚本,wepoker辅助工具,确实真的是有挂(的确有挂)1、wepoke...
玩家必备科普!wepoker私... 玩家必备科普!wepoker私人局辅助,wpk真吗,一直真的有挂(有挂猫腻)玩家必备科普!wepok...
玩家必看教程!hhpoker是... 玩家必看教程!hhpoker是真的吗,wpk辅助软件,真是真的是有挂(确实有挂)1、下载好正确养号方...
揭秘攻略!德普之星透视辅助插件... 揭秘攻略!德普之星透视辅助插件,德州局脚本,原来真的是有挂(证实有挂)1、在插件功能辅助器技巧中,中...
教程攻略!pokerrrr2辅... 教程攻略!pokerrrr2辅助,wepoker辅助器官方,一贯是真的有挂(发现有挂)1、每一步都需...
我来分享!wepokerplu... 我来分享!wepokerplus辅助,wepoker黑侠破解,一直有挂(有挂方式)1、任何透视是真的...
9分钟了解!we-poker辅... 9分钟了解!we-poker辅助软件教程,购买的wpk辅助在哪里下载,真是是有挂(有挂细节)1、让任...
我来教教你!德普之星辅助工具如... 我来教教你!德普之星辅助工具如何打开,德州透视插件,真是是真的有挂(有挂功能)1、有没有辅助教程、有...
必备科技!we-poker辅助... 必备科技!we-poker辅助软件教程,购买的wpk辅助在哪里下载,真是存在有挂(今日头条)暗藏猫腻...
玩家亲测!hhpoker买挂,... 玩家亲测!hhpoker买挂,wepoker私人局辅助器怎么用,竟然是真的有挂(有挂细节)1)wep...