• Java 中的值传递和引用传递问题


    Java 中的值传递和引用传递问题

    public class Operation {
        int data = 50;
    
        void change(int data) {
            data = data + 100;
        }
    
        public static void main(String[] args) {
            Operation op = new Operation();
            System.out.println("before change: " + op.data);
            op.change(200);
            System.out.println("after change: " + op.data);
        }
    }
    

    点击查看结果

    ``` before change: 50 after change: 50 ```
    public class Operation2 {
        int data = 50;
    
        void change(Operation2 op) {
            op.data = op.data + 100;
        }
    
        public static void main(String args[]) {
            Operation2 op = new Operation2();
            System.out.println("before change " + op.data);
            op.change(op);
            System.out.println("after change " + op.data);
        }
    }
    

    点击查看结果

    ``` before change 50 after change 150 ```

    Dog 类

    ``` public class Dog { String name;
    Dog(String name) {
        this.name = name;
    }
    
    String getName() {
        return this.name;
    }
    
    void setName(String name) {
        this.name = name;
    }
    
    String getObjectAddress() {
        return super.toString();
    }
    

    }

    </div>
    
    ```java
    public class PassByValueExample {
        public static void main(String[] args) {
            Dog dog = new Dog("A");
            System.out.println(dog.getObjectAddress());
            System.out.println("------------------------");
            func(dog);
            System.out.println("------------------------");
            System.out.println(dog.getObjectAddress());
            System.out.println(dog.getName());
        }
    
        private static void func(Dog dog) {
            System.out.println(dog.getObjectAddress());
            dog = new Dog("B");
            System.out.println(dog.getObjectAddress());
            System.out.println(dog.getName());
        }
    }
    

    点击查看结果

    ``` Dog@1b6d3586 ------------------------ Dog@1b6d3586 Dog@4554617c B ------------------------ Dog@1b6d3586 A

    Process finished with exit code 0

    </div>
    
    ```java
    public class PassByValueExample2 {
        public static void main(String[] args) {
            Dog dog = new Dog("A");
            func(dog);
            System.out.println(dog.getName());
        }
    
        private static void func(Dog dog) {
            dog.setName("B");
        }
    }
    

    点击查看结果

    ``` B ```
  • 相关阅读:
    彩食鲜架构团队风采
    钉钉的sonar集成通知
    django学习,session与cookie
    flask框架
    logging日志从开始到放弃
    你这么年轻,总得做些什么吧(致那些还未定型的程序员)
    悲观锁,乐观锁
    商城中的猜你喜欢是怎么实现的
    MemCache与redis
    如何使用go打出hell word
  • 原文地址:https://www.cnblogs.com/hgnulb/p/10093350.html
Copyright © 2020-2023  润新知