zoukankan      html  css  js  c++  java
  • 值传递和引用传递的小例子

    代码:

    public class Demo {
    
        public static void main(String[] args) {
            // 引用传递示例
            Student student = new Student();
            student.setName("lisi");
            student.setSex("girl");
            new Method().test1(student); // entity的值发生了变化
            System.out.println(student.getName() + "," + student.getSex()); // 输出结果:zhangSan,boy
    
            // 值传递示例
            // String传递的也是引用副本的传递,但是因为String为final的,所以和按值传递等同的
            String str = new String("123");
            new Method().test2(str); // str的值没有发生变化
            System.out.println(str); // 输出结果: 123
        }
    
    }
    
    class Method {
    
        /**
         * 引用传递
         */
        public void test1(Student entity) {
            entity.setName("zhangSan");
            entity.setSex("boy");
        }
    
        /**
         * 值传递
         */
        public void test2(String str) {
            str = "abc";
        }
    }
    
    class Student {
    
        private String name;
    
        private String sex;
    
        public Student() {
            super();
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getSex() {
            return sex;
        }
    
        public void setSex(String sex) {
            this.sex = sex;
        }
    }
  • 相关阅读:
    磁盘
    磁盘接口
    Linux help websites
    [SOJ] 1282. Computer games (KMP)
    [SOJ]1753 解码
    hdu 3473 裸的划分树
    hdu 4417 划分树
    hdu 4665 搜索
    hdu 4340 树状DP
    hdu 4005 边连通度与缩点
  • 原文地址:https://www.cnblogs.com/zj0208/p/5856994.html
Copyright © 2011-2022 走看看