java中this的用法

来源:互联网 发布:远程桌面控制软件 编辑:程序博客网 时间:2024/05/27 19:27


用类名定义一个变量的时候,定义的应该只是一个引用,外面可以通过这个引用来访问这个类里面的属性和方法,那们类里面是够也应该有一个引用来访问自己的属性和方法纳?呵呵,JAVA提供了一个很好的东西,就是 this 对象,它可以在类里面来引用这个类的属性和方法。

this:指代当前对象,哪个对象调值的就是哪个对象

          在方法中(包括构造方法)访问成员变量前默认有个this.

范例:Cell c = new Cell();

    c.row = 2;

    c.col = 5;

    c.drop();

    c.moveLeft(3);

    String str = c.getCellInfo();

    class Cell{

       int row;

       int col;

       void drop(){

       this.row++;//相当于c.row++;     在方法中访问成员变量前默认有个this.

       void moveLeft(int n){

       this.col-=n;// 相当于c.col-=n;     在方法中访问成员变量前默认有个this.

}

}

}


  this的用法:

          1)this.成员变量---------访问成员变量


范例:成员变量:写在类中,方法外

         局部变量:方法中

         成员变量和局部变量可以同名

class Cell{

    int row;

    int col;

    Cell(int row,int col){

         this.row = row;

         this.col  = col;

    }

}



Cell c = new Cell(2,5);//相当于Cell c = new Cel();

                                          c.row = 2;

                                          c.col = 5;

class Cell{

     int row;

     int col;

Cell(int row,int col){

     this.row = row; //   c.row =2;

     this.col = col;//   c.col = 5;

   }

     void drop(){

           this.row++;//   c.row = c.row+1;

   }

}


          2)this.方法名()------调用方法(一般不用)

          3)this()----------------调用构造方法(没有点!!!)


Cell c1 = new Cell();

Cell c2 = new Cell(3);

Cell c3 = new Cell(2,5);


class Cell{

int row;

int col;

Cell(){

    row = 0;

    col =0;

}

Cell(int n){

   row = 0;

   col  = 0;

}

Cell(int n){

row = n;//       this(n,n);调构造方法Cell(int row,int col)

col = n;

Cell(int row,int col){

this.row = row;//       重名时不能省略

this.col = col;

}

}

}


1 0
原创粉丝点击