通常写this的时候,都是指“这个对象”或者“当前对象”,而它本身表示对当前对象的引用。
1.当成员变量名与局部变量名相同时,会产生歧义,此时用 this.成员变量名 表示成员变量
public class ThisDemo01{
String name = "Jack";
public void print(String name){
System.out.println("局部变量值 = "+name);
System.out.println("成员变量值 = "+this.name);//this.name表示成员变量
this.name = name;
System.out.println("改变成员变量后 = "+this.name);
}
public static void main(String[] args){
ThisDemo01 td = new ThisDemo01();
td.print("Rose");
}
}
输出结果:
局部变量值 = Rose
成员变量值 = Jack
改变成员变量后 = Rose
class Water{
public Water(){
new Person().drinkWater(this);
}
}
class Person{
public void drinkWater(Water wt){//将Water对象传递过来
System.out.println("喝水成功");
}
}
public class ThisDemo02{
public static void main(String[] args){
new Water();
}
}
3.在构造方法中调用另一个构造方法class Person{
String name;
int age;
public Person(String name){
this.name = name;
}
public Person(String name,int age){
this(name);
this.age = age;
}
public void print(){
System.out.println("姓名:"+name+" 年龄: "+age);
}
}
public class ThisDemo03{
public static void main(String[] args){
Person per = new Person("Jack",30);
per.print();
}
}
4.在内部类或匿名内部类中调用外部类方法,有两种情况
第一种:外部类、匿名内部类两者没有重名方法,则内部匿名类自动获得外部类的成员变量和方法的调用权限
第二种:外部类、匿名内部类两者有重名方法,则通过this可以获取外部类的重名方法
public class ThisDemo04{
public void run(){
System.out.println("我是外部类run方法");
}
public ThisDemo04(){
Thread thread = new Thread(){
public void run(){
<span style="color:#ff0000;"><strong>ThisDemo04.this.run();</strong></span>
System.out.println("我是内部类run方法");
}
};
thread.start();
}
public static void main(String[] args){
new ThisDemo04();
}
}
除此之外,还可以将外部类run()声明成static,这样内部类可以直接调用。public class ThisDemo04{
public<span style="color:#ff0000;"><strong> static</strong></span> void run(){
System.out.println("我是外部类run方法");
}
public ThisDemo04(){
Thread thread = new Thread(){
public void run(){
<span style="color:#ff0000;"><strong>ThisDemo04.run();</strong></span>
System.out.println("我是内部类run方法");
}
};
thread.start();
}
public static void main(String[] args){
new ThisDemo04();
}
}