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;
        }
    }
  • 相关阅读:
    HTML5元素标记释义
    Mvc使用Partial View 来封装上传控件
    订单页过滤,sql写法
    防止提交重复订单的方法
    查询数据库所有列
    asp.net 异常处理
    7. DateTime,TimeSpan
    8.1.thread
    8.2.Task
    2.2. Array
  • 原文地址:https://www.cnblogs.com/zj0208/p/5856994.html
Copyright © 2011-2022 走看看