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

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

相关内容

热门资讯

透视方针!wejoker免费脚... 您好,wejoker免费脚本这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】...
经核实!微乐小程序免费黑科技,... 经核实!微乐小程序免费黑科技,微信微乐辅助插件(透视)原来有辅助技巧(哔哩哔哩)1、完成有辅助插件,...
透视方针!德州透视插件(WPK... 透视方针!德州透视插件(WPK辅助器)都是是有辅助工具(哔哩哔哩)1、德州透视插件免费辅助多个强度级...
随着!微乐小程序免费黑科技,微... 随着!微乐小程序免费黑科技,微信小程序辅助器免费版(透视)好像是真的辅助教程(哔哩哔哩)1、用户打开...
透视办法!werplan外开挂... 透视办法!werplan外开挂(HHpoker控制)原来真的有辅助工具(哔哩哔哩);暗藏猫腻,小编详...
迎来新发展!微信微乐游戏辅助脚... 迎来新发展!微信微乐游戏辅助脚本,微信小程序游戏破解微乐辅助(透视)竟然真的是有辅助app(哔哩哔哩...
透视方案!wepoker手机版... 透视方案!wepoker手机版辅助(HHpoker下载)真是是真的有辅助方法(哔哩哔哩)1、wepo...
2026版教程!微乐小程序免费... 2026版教程!微乐小程序免费黑科技,微乐小程序插件免费(透视)本来是真的辅助插件(哔哩哔哩)1、上...
透视秘籍!德州机器人代打脚本(... 透视秘籍!德州机器人代打脚本(HHpoker插件)一直真的有辅助脚本(哔哩哔哩)1、不需要AI权限,...
插件辅助挂!微乐小程序黑科技,... 插件辅助挂!微乐小程序黑科技,微乐家乡小程序自建房辅助app(透视)都是是真的辅助教程(哔哩哔哩);...