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

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

相关内容

热门资讯

今年以来!wepoker透视脚... 您好,wepoker透视脚本苹果版这款游戏可以开挂的,确实是有挂的,需要了解加去威信【4852750...
来临!wepoker模拟器哪个... 来临!wepoker模拟器哪个,wepoker透视脚本免费,妙计教程(有挂工具)1、每一步都需要思考...
黑科技技巧!pokemmo手机... 黑科技技巧!pokemmo手机版透视脚本,poker红龙辅助,步骤教程(存在有挂)一、pokemmo...
目前!线上德州的辅助器是什么,... 目前!线上德州的辅助器是什么,wepoker怎么设置盖牌,步骤教程(有挂分享)1、线上德州的辅助器是...
此事迅速冲上热搜!wepoke... 此事迅速冲上热搜!wepokerplus透视脚本免费,hh poker插件下载,技法教程(有挂技术)...
2026版方法!pokemmo... 2026版方法!pokemmo辅助器脚本下载,德州局HHpoker透视脚本,学习教程(了解有挂)1、...
经调查!智星德州可以透视吗,w... 经调查!智星德州可以透视吗,wpk有作弊吗,法子教程(确实有挂)1、智星德州可以透视吗有没有辅助教程...
备受关注的!wepoker代打... 备受关注的!wepoker代打辅助机器人,epoker透视底牌,机巧教程(有挂猫腻)1、超多福利:超...
围绕透视问题!wepokerp... 围绕透视问题!wepokerplus透视脚本免费,hh poker辅助器先试用,妙计教程(真实有挂)...
现就发布提示!拱趴大菠萝挂怎么... 现就发布提示!拱趴大菠萝挂怎么安装,wepoker祈福有用吗,指南书教程(有挂工具)拱趴大菠萝挂怎么...