关于变量的作用域04想要改变一个对象属性的正确方法

来源:互联网 发布:淘宝主播机构招聘信息 编辑:程序博客网 时间:2024/06/05 07:40

package Quote;

class BirthDate {
    private int day;
    private int month;
    private int year;
   
    public BirthDate(int d, int m, int y) {
        day = d;
        month = m;
        year = y;
    }
   
    public void setDay(int d) {
     day = d;
   }
   
    public void setMonth(int m) {
     month = m;
    }
   
    public void setYear(int y) {
     year = y;
    }
   
    public int getDay() {
     return day;
    }
   
    public int getMonth() {
     return month;
    }
   
    public int getYear() {
     return year;
    }
   
    public void display() {
     System.out.println
        (day + " - " + month + " - " + year);
    }
}


public class BithdayVariable{
    public static void main(String args[]){
        BithdayVariable test = new BithdayVariable();
        int date = 9;
        BirthDate d1= new BirthDate(7,7,1970);
        BirthDate d2= new BirthDate(1,1,2000);   
        test.change1(date);
        //这个形参date也是stack 中的局部变量
        //调用方法的时候,将date的值传递给 stack中的局部变量i i=9 操作的是一个副本
        //之后i变成1234 ; 方法调用完成之后局部变量i消失
        //方法白调用了
        test.change2(d1);
        //这个d1 也是stack 中的局部变量 指向heap中 new 出来的一个对象
        //方法的局部变量形参b 也指向 d1指向的对象
        //之后呢 b  不指向原来那对象了 而指向new出来的那个新对象
        //方法调用完了, 局部变量b消失 指向的new出来的那个对象也消失
        //方法白调用了
        test.change3(d2);
        //改变了 对象中的值
        System.out.println("date=" + date);
        d1.display();
        d2.display();
    }
   
    public void change1(int i){
     i = 1234;
    }
   
    public void change2(BirthDate b) {
     b = new BirthDate(22,2,2004);
    }
      
    public void change3(BirthDate b) {
     b.setDay(22);
    }
}

原创粉丝点击