this关键字的使用(十分详细)——Java

this关键字:有三种用法:

1、this.属性名
2、this.方法名
3、this()访问构造函数

一、this.属性名
使用情形:如果方法里有个局部变量和成员变量同名,但程序又需要访问这个被覆盖的成员变量,则必须使用this关键字。

public class A{
private String name;
private int id;
public A(String name){
this.name=name;
}
}
结论:当一个类的属性名与访问该属性的方法参数名相同时,则需要使用this关键字来访问类中的属性,以区分类的属性和方法中的参数。

二、this.方法名
使用情形:让类中的一个方法,访问该类里的另一个方法或实例变量。
this关键字的使用(十分详细)——Java
this关键字的使用(十分详细)——Java注意:static关键字是对类而言,this是对具体的对象,因此static修饰的方法中不能使用this引用。

三、this()访问构造函数
使用情形:
this()用来访问本类的构造方法,括号中可以又参数,如果又参数就是调用指定的有参构造函数。

public class A{
private String name;
private int id;
public A(String name){
this.name=name;
}
public A(){
this(“Zhang”);//this调用真正构造函数A(String name)
}
}

注意:

  • this()不能在普通方法中使用,只能写在构造方法中
  • 在构造方法中使用时必须是第一条语句
  • 不能与super()同时使用,它们都要在第一行