Java this关键字
this 关键字
this是什么,在内存方面是怎样的?
1、一个对象一个this。
2、this是一个变量,是一个引用。this保存当前对象的内存地址,指向自身。
所以,严格意义上来说,this代表的就是“当前对象”
3、this存储在堆内存当中对象的
4、this只能使用在实例方法中。谁调用这个实例方法,this就是谁。
所以this代表的是:当前对象。
在调用方法的时候,会默认传一个this,代表当前对象
5、“this.”大部分情况下是可以省略的。
6、为什么this不能使用在静态方法中??????
this代表当前对象,静态方法中不存在当前对象。 可以在静态方法中new一个对象,访问
7、什么时候不能省略 this
在实例方法中,或者构造方法中,为了区分局部变量和实例变量,
这种情况下:this. 是不能省略的。
public void setNo(int no){ //no是局部变量 //this.no 是指的实例变量。 this.no = no; // this. 的作用是:区分局部变量和实例
8、this除了可以使用在实例方法中,还可以用在构造方法中
新语法:通过当前的构造方法去调用另一个本类的构造方法,可以使用以下语法格式:
this(实际参数列表);
通过一个构造方法1去调用构造方法2,可以做到代码复用。但需要注意的是:“构造方法1”和“构造方法2” 都是在同一个类当中。
死记硬背:
对于this()的调用只能出现在构造方法的第一行。只能有一个 this() 语句。
class Date{ // 以后写代码都要封装,属性私有化,对外提供setter and getter //年 private int year; //月 private int month; //日 private int day; // 构造方法无参 // 调用无参数构造方法,初始化的日期是固定值。 public Date(){ //错误: 对this的调用必须是构造器中的第一个语句 //System.out.println(11); /* this.year = 1970; this.month = 1; this.day = 1; */ this(1970, 1, 1); } // 构造方法有参数 public Date(int year, int month, int day){ this.year = year; this.month = month; this.day = day; } // 提供一个可以打印日期的方法 public void detail(){ //System.out.println(year + "年" + month + "月" + day + "日"); System.out.println(this.year + "年" + this.month + "月" + this.day + "日"); } //setter and getter public void setYear(int year){ // 设立关卡(有时间可以设立关卡) this.year = year; } public int getYear(){ return year; } public void setMonth(int month){ // 设立关卡(有时间可以设立关卡) this.month = month; } public int getMonth(){ return month; } public void setDay(int day){ // 设立关卡(有时间可以设立关卡) this.day = day; } public int getDay(){ return day; } }
PS:
程序再怎么变化,万变不离其宗,有一个固定的规律:
所有的实例相关的都是先创建对象,通过“引用.”来访问。
所有的静态相关的都是直接采用“类名.”来访问。
大结论:
只要负责调用的方法a和被调用的方法b在同一个类当中:
this. 可以省略
类名. 可以省略