this是什么?
- this是一个引用类型,保存了内存地址
- 在堆中,每一个对象都有this,this保存的地址指向自身
this用在哪里?
- 可以用在成员方法中。谁去调用这个成员方法,this就代表谁,this就指当前对象
- 可以用在构造方法中。
语法:this(实参);
通过一个构造方法去调用另一个构造方法
目的:代码重用
//需求:在创建日期对象的时候,默认的日期是:1970年1月1日
Class MyDate{
//Field
int year;
int month;
int day;
//Constructor
MyDate(){
this(1970,1,1);//调用下面的构造函数。必须写在构造方法第一行,等同于下面的三行。
/*
this.year=1970;
this.month=1;
this.day=1;
*/
}
MyDate(int _year,int _month,int _day){
year=_year;
month=_month;
day=_day;
}
}
- this还可以用来区分成员变量和局部变量
class Manager{
//Field
private String name;
//Constructor
Manager(){}
Manager(String name){
this.name=name;
}
//Method
//成员方法
public void setName(String name){
this.name=name;
}
}
- this不能用在静态方法中。静态方法的执行只需要类名.,不需要对象的存在,而this代表的是当前对象,所以静态方法中没有this。
class Manager{
//Field
String name;
//Constructor
Manager(){}
Manager(String name){
this.name=name;
}
//静态方法
public static void m1(){
//System.out.println(this.name);不合法,静态方法中没有this
//System.out.println(name);不合法,成员变量只能用 引用. 访问
//如果想要访问name只能:
Manager man1=new Manager("Tom");
System.out.println(man1.name);
}
}