一、什么是this
先看一个简单示例:
public class Main{
public static void main(String[] args){
Person p1 = new Person("shimisi",80);
}
}
//构造器
class Person{
String name;
int age;
public Person(String name,int age)
{
this.name = name;
this.age = age;
System.out.println(name +"\t"+ age);
}
}
二、this的注意事项和使用细节
1.哪个对象调用,this就代表哪个对象
this关键字:
1.this关键字可以用来访问本类的属性、方法、构造器
2.this用于区分当前类的属性和局部变量
3.访问成员方法的语法:this.方法名(参数列表);
4.访问构造器语法:this(参数列表); 注意只能在构造器中使用
5.this不能在类定义的外部使用,只能在类定义的方法中使用。
2.this快速入门:this访问构造器
//构造器快速入门
public class Main{
public static void main(String[] args){
T t1 = new T();
}
}
//构造器
class T{
public T()
{
//访问T(String name,int age)
//如果有this访问构造器,必须放在第一条语句
this("jake",18);
System.out.println("T()构造器");
}
public T(String name,int age)
{
System.out.println("T(String name,int age)构造器");
}
}
3.传统方法访问用就近原则
而this只关注于属性
public class Main{
public static void main(String[] args){
T t1 = new T();
t1.m();
}
}
//构造器
class T{
String name = "jack";
int age = 18;
public void m()
{
String name = "smith";
System.out.println("name " + name + " age " + age);//name = smith
System.out.println("this.name " + this.name + " this.age " + this.age);
//this.name = jack
}
}