zoukankan      html  css  js  c++  java
  • 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 ```
  • 相关阅读:
    NuGet包介绍
    修改逻辑文件名
    检查扫描文件系统
    C# Newtonsoft.Json不序列字段
    HierarchyId通过父节点创建一个新的子节点
    常用SQL语句
    redis脚本
    asp.net 的一个简单进度条功能
    .Net C#向远程服务器Api上传文件
    使用IKVM在C#中调用JAVA程序
  • 原文地址:https://www.cnblogs.com/hgnulb/p/10093350.html
Copyright © 2011-2022 走看看