java中this的用法_java中this的用法



用类名定义一个变量的时候,定义的应该只是一个引用,外面可以通过这个引用来访问这个类里面的属性和方法,那们类里面是够也应该有一个引用来访问自己的属性和方法纳?呵呵,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;

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值