不同类型的方法传递
创始人
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
    

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

相关内容

热门资讯

重大推荐作弊器教程!中至余干麻... 重大推荐作弊器教程!中至余干麻将多功能作弊器教程,中至余干麻将真是真的有作弊器教程中至余干麻将辅助器...
玩家亲测作弊器脚本!边锋cr在... 玩家亲测作弊器脚本!边锋cr在线多功能作弊器脚本,边锋cr在线竟然有作弊器脚本1、实时边锋cr在线透...
玩家攻略推荐开挂教程!禾沐多功... 玩家攻略推荐开挂教程!禾沐多功能开挂教程,禾沐一直是有开挂教程禾沐是不是有人用挂微扑克wpk插件教程...
终于懂了开挂方法!打两圈兴化麻... 终于懂了开挂方法!打两圈兴化麻将多功能开挂方法,打两圈兴化麻将真是存在有开挂方法1、玩家可以在打两圈...
科普作弊器方法!大唐麻将全集多... 科普作弊器方法!大唐麻将全集多功能作弊器方法,大唐麻将全集一贯有作弊器方法1)大唐麻将全集有没有挂:...
重大通报辅助方法!边锋老友棋牌... 重大通报辅助方法!边锋老友棋牌多功能辅助方法,边锋老友棋牌好像存在有辅助方法1、进入到边锋老友棋牌是...
推荐攻略开挂教程!宁夏麻将多功... 推荐攻略开挂教程!宁夏麻将多功能开挂教程,宁夏麻将真是是真的有开挂教程1、完成宁夏麻将辅助器v3.3...
总算了解透视挂技巧!彩虹沁阳麻... 总算了解透视挂技巧!彩虹沁阳麻将多功能透视挂技巧,彩虹沁阳麻将果然真的有透视挂技巧1、彩虹沁阳麻将模...
我来分享辅助脚本!边锋cr在线... 我来分享辅助脚本!边锋cr在线多功能辅助脚本,边锋cr在线竟然存在有辅助脚本运边锋cr在线辅助工具,...
程序员教你作弊器攻略!欢乐赣游... 程序员教你作弊器攻略!欢乐赣游GZ多功能作弊器攻略,欢乐赣游GZ原来存在有作弊器攻略1、起透看视 欢...