学习笔记:this关键字

1.定义:

this代表所在类的当前对象

代码理解:

**public** **class** This01 {

**public** **static** **void** main(String[] args) {

Dogg dog1 = **new** Dogg("大壮",3);

System.**out**.println("dog1.hashCode="+dog1.hashCode());

dog1.info();

Dogg dog2 = **new** Dogg("大黄",2);

dog2.info();

System.**out**.println("dog2.hashCode="+dog2.hashCode());

}

}

**class** Dogg{

**public** String name;

**public** **int** age;

**public** Dogg(String name,**int** in_age) {

**this**.name = name;

**this**.age = in_age;

System.**out**.println("this.hashCode="+**this**.hashCode());

}

<!--`hashCode返回对象的哈希值-->

**public** **void** info() {

System.**out**.println("this.hashCode="+**this**.hashCode());

System.**out**.println(**this**.name+"\t"+**this**.age);

}

}

输出:

this.hashCode=315138752

dog1.hashCode=315138752

this.hashCode=2114874018

dog2.hashCode=2114874018

小结:

哪个对象调用,this就代表哪个对象

2.使用细节

(1)this关键字可以访问本类的属性、方法、构造方法。

(2)this用于区分当前类的属性和局部变量。

(3)访问成员方法的语法:this.方法名(参数列表);

(4)访问构造方法语法:this(参数列表);注意只能在构造方法中使用(即只能在构造方法中 访问另外一个构造方法,必须放在第一条语句)。

(5)this不能在类定义的外部使用,只能在类定义的方法中使用

代码理解:

**public** **class** This02 {

**public** **static** **void** main(String[] args) {

T05 t1 = **new** T05();

t1.f2();

}

}

**class** T05{

<!--`<!--访问构造方法语法:this(参数列表);注意只能在构造方法中使用`-->-->

<!--`(即只能在构造方法中 访问另外一个构造方法`-->

<!--<!--`注意:访问构造器语法:this(参数列表);必须放在第一条语句-->`-->

**public** T05() {

<!--`这里访问T05(String name,int age)`-->

**this**("jack",100);

System.**out**.println("T05() 构造方法");

}

**public** T05(String name,**int** age) {

System.**out**.println("T05(String name,int age) 构造方法");

}

<!--`访问成员方法的语法:this.方法名(参数列表);`-->

**public** **void** f1() {

System.**out**.println("f1() 方法..");

}

**public** **void** f2() {

System.**out**.println("f2() 方法..");

<!--`调用本类的f1`-->

<!--`第一种方法`-->

f1();

<!--第二种方法-->`

**this**.f1();

}

}

输出结果:

T05(String name,int age) 构造方法

T05() 构造方法

f2() 方法..

f1() 方法..

f1() 方法..

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值