作用:
1、调用本类中的方法
2、表示类中的属性
3、可以使用this调用本类的构造方法
4、this表示当前对象
1、调用本类中的方法
public class ThisDemo {
public static void main(String[] args) {
DemoThis d=new DemoThis(20);
d.tellThis();
}
}
class DemoThis{
private int age;
public DemoThis(int a) {
age=a;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void tellThis() {
System.out.println("年龄为:"+this.getAge());
}
}
//结果:年龄为:20
使用“this.方法名称()”格式可以调用本类中的方法
2、表示类中的属性
class DemoThis{
private int age;
public DemoThis(int age) {
this.age=age;
}
//等价于
/*public DemoThis(int a) {
age=a;
}*/
..........
}
如果构造方法中这样写
public DemoThis(int age) {
age=age;
}
其中“age=age”都是构造方法的参数——可以通过“就近原则”分析原理。
3、可以使用this调用本类的构造方法
//此程序中通过this()调用的某类的无参构造方法。
public class ThisDemo {
public static void main(String[] args) {
//构造方法在实例化对象时自动被调用
//即,在类的所以方法中构造方法是被优先调用
DemoThis d=new DemoThis(20);
}
}
class DemoThis{
private int age;
public DemoThis(int age) {
this(); //调用无参构造方法
this.age=age;
}
public DemoThis() {
System.out.println("此无参构造方法会被this()调用");
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
this调用构造方法必须也只能放在构造方法的首行
this调用构造方法时一定要留一个构造方法作为出口,即程序中至少有一个构造方法未使用this调用其他构造方法——一般将无参构造方法作为出口。
4、this表示当前对象(this最重要的特点)
Java当前对象:指当前正在调用类中方法的对象。
解释:
假设现在有张三、李四两人,如果现在在吃饭的人是张三,则“当前正在吃饭的人”是张三。
比较对象是否相等步骤
1、首先比较对象地址是否相等
2、若地址不相等,比较属性。
public class ThisDemo02 {
public static void main(String[] args) {
// TODO Auto-generated method stub
PersonThis p1=new PersonThis("张三",16);
PersonThis p2=new PersonThis("张三",16);
if(p1.compare(p2)) {
System.out.println("两对象的在地址和属性上全相同");
}else {
System.out.println("两对象不完全相同");
}
}
}
class PersonThis{
private String name;
private int age;
public PersonThis(String name,int age) {
this.name=name;
this.age=age;
}
public boolean compare(PersonThis per) {
PersonThis p1=this; //表示当前调用方法的对象——此时谁调用compare(),this就表示谁
PersonThis p2=per; //传递到方法的对象
//首先堆地址进行判断
if(p1==p2) {
return true;
}
//对对象的属性进行判断
if(p1.name.equals(p2.name)&&p1.age==p2.age) {
return true;
}else {
return false;
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
在程序中可能存在多个对象,此时通过this就能表示当前对象
假设对象A调用了类中的方法function(),那么这个function()中的 this就为当前执行的对象A。