美文网首页
值传递,引用传递

值传递,引用传递

作者: 临木有希 | 来源:发表于2018-08-01 13:18 被阅读0次
    //值传递
    
    public class ValueDemo{
         public static void main(String[] args){
             int x=10;
             method(x);
             System.out.println("x="+x);
         }
         public static void method(int mx){
             mx=20;
         }
        
    }
    
    image.png
    //示例二:引用传递
    public class RefDemo1{
        public static void main(String[] args){
            Duck d = new Duck();
            method(d);
            System.out.println("Duck age ="+d.age);
        }
        public static void method(Duck duck){
            duck.age = 5;
        }   
    }
    
    class Duck{
        int age = 2;//省略封装
    }
    
    image.png
    /**示例三:String传递
        字符串本身就是一个对象
    */
    public class RefDemo2{
        public static void main(String[] args){
            String name ="小飞";
            method(name);
            System.out.println("name ="+name);
        }
        public static void method(String sname){
            sname = "小备";
        }   
    }
    
    image.png
    //示例三:String传递
    public class RefDemo3{
        public static void main(String[] args){
            Person p = new Person();
            method(p);
            System.out.println("person name ="+p.name);
        }
        public static void method(Person per){
            per.name = "备备";
        }   
    }
    
    class Person{
        String name ="飞飞";//省略封装
    }
    
    image.png

    <meta charset="utf-8">

    <meta charset="utf-8">

    clipboard.png

    相关文章

      网友评论

          本文标题:值传递,引用传递

          本文链接:https://www.haomeiwen.com/subject/gwnlvftx.html