This关键字
什么是this?
1 、this 是一个变量 ,一个引用。
this 保存的就是当前对象的地址,指向对象本身,即this 代表的就是“当前对象”。
2 、this 存储在堆内存中,存在于对象的内部。
3 、this 只能用在实例方法中,谁调用这个实例方法,this 就是“谁自己”。
4 、this 不能出现在静态方法中
因为this 代表当前对象,静态方法中不存在当前对象
强行调用会出现错误: 无法从静态上下文中引用非静态 变量 this
5 、大多数情况下,this 可以省略
例子区分实例变量和静态变量
public class Test {
int i = 0 ;
static int num = 123 ;
public static void main ( String[ ] args) {
System. out. println ( new Test ( ) . i) ;
System. out. println ( "=========================" ) ;
System. out. println ( Test. num) ;
System. out. println ( "省略类名——>" + num) ;
}
}
this什么时候“不可省略”?
在实例方法中,或者构造方法中,为了区分局部变量和实例变量,
这种情况下:this . 是不能省略的。
例子
package com. blog;
public class Student {
Integer age;
String name;
public Student ( ) {
}
public Student ( Integer age, String name) {
this . age = age;
this . name = name;
}
public Integer getAge ( ) {
return age;
}
public void setAge ( Integer age) {
this . age = age;
}
public String getName ( ) {
return name;
}
public void setName ( String name) {
this . name = name;
}
}
例子3(证明就近原则)
Student类
public class Student {
Integer age;
public Student ( ) {
}
public Student ( String name) {
this . age = age;
}
public Integer getAge ( ) {
return age;
}
public void setAge ( Integer age) {
age = age;
}
}
Test方法
public class Test {
public static void main ( String[ ] args) {
Student student = new Student ( ) ;
student. setAge ( 18 ) ;
System. out. println ( student. getAge ( ) ) ;
}
}
This使用在构造方法中
1 、通过当前的构造方法去调用另一个本类的构造方法,可以使用以下语法格式:
this ( 实际参数列表) ;
通过一个构造方法1 去调用构造方法2 ,可以做到代码复用。
但需要注意的是:“构造方法1 ”和“构造方法2 ” 都是在同一个类当中。
2 、this ( ) 这个语法作用是什么?
代码复用。
3 、'对于this()的调用只能出现在构造方法的第一行' 。
例子(构造方法的相互调用)
Student类
package com. blog;
public class Student {
private Integer age;
private String name;
public Student ( ) {
this ( 18 , "张三" ) ;
}
public Student ( Integer age, String name) {
this . age = age;
this . name = name;
}
@Override
public String toString ( ) {
return "学生信息:{" +
"姓名 = " + name +
", 年龄 = '" + age + '\'' +
'}' ;
}
public Integer getAge ( ) {
return age;
}
public void setAge ( Integer age) {
this . age = age;
}
public String getName ( ) {
return name;
}
public void setName ( String name) {
this . name = name;
}
}
Test方法
public class Test {
public static void main ( String[ ] args) {
Student student = new Student ( ) ;
System. out. println ( student) ;
}
}