this:代表对象本身(已经存在对象、即将创建的对象 -->操作对象)
1、this.属性: 区分属性与局部变量同名
2、this.方法(实参) :成员方法间相互调用
3、this([实参]) :构造器首行,构造器之间相互调用
4、this单独使用: 经常用于比较或者查看hashcode
注意:每个成员方法|构造器隐式包含this参数
1. this:代表对象本身,谁调用代表谁
2. this不能直接使用在静态方法中
3. 当前类中,类.this可以省略。
4. 构造器中避免出现递归调用,解决方法:至少有一个方法没有this([])
解析一、
package com.zad.my_this;
/**
* 每个成员方法|构造器隐式包含this参数
* this: 代表对象本身,谁调用代表谁
* this不能使用在静态方法中
* 1、this.属性 :访问对象的属性 ,区分 形参与属性同名
* 2、this.方法([实参]) :成员方法调用
* 3、this([实参]) : 构造器重载时,相互调用
* 注意:必须放在构造器首行
* 4、this 单独使用时,用于比较
* @author zhongaidong
*/
public class ThisDemo01 {
public int n = 0;
public String str = "abc";
// 对对象进行了初始化
ThisDemo01() {
// this.属性
// /*ThisDemo01.this.*/n = 20;
// 构造器首行
this(20);
}
ThisDemo01(int n) {
// this.属性
ThisDemo01.this.n = n;
System.out.println(n);
}
public void p() {
// this.方法([实参])
this.test();
}
public void test(/* ThisDemo01 this */) {
this.n = 30;
System.out.println(this);
}
public static void main(String[] args) {
ThisDemo01 demo = new ThisDemo01();
System.out.println(demo + "-->");
System.out.println(demo.n);
demo.test();
System.out.println(demo.n);
// this 不能直接使用在静态方法中
// ThisDemo01 dem02 = this;
}
}
解析二、
package com.zad.my_this;
/**
* 构造器中避免出现递归调用
* 解决方法:让至少一个方法没有this([])
* @author zhongaidong
*/
public class ThisDemo02 {
public int n = 0;
public String str = "abc";
ThisDemo02(){
this(20);
}
ThisDemo02(int n){
this(n,"30");
}
ThisDemo02(int n, String str){
// this(n); --> 这样会导致递归调用
this.n = n;
this.str = str;
}
public static void main(String[] args){
}
}
解析三、
package com.zad.my_this;
/**
* this 单独使用时,用于比较
*
* @author zhongaidong
*/
public class ThisDemo03 {
public static void main(String[] args) {
Book b1 = new Book("test",20);
Book b2 = new Book("test",20);
System.out.println(b1 == b2);
System.out.println(b1.equals(b2));
}
}
// 图书上架,业务规则:名称相同 + 价格相同
class Book{
public String name;
public double price;
public Book(){
}
public Book(String name, double price){
this.name = name;
this.price = price;
}
// 比较内容相同
public boolean equals(/* Book this, */ Book b2){
// 地址相同,内容一定相同
if(this == b2){
return true;
}
// 名称相同 + 价格相同
if(this.name.equals(b2.name) && this.price == b2.price){
return true;
}
return false;
}
}