一、this关键字的意义
1、代表当前对象
2、this就是所在函数所属对象的引用,简单来说,哪个对象调用了this所在 的函数 this就代表哪个对象
二、this关键字的应用
(一个类中除静态外的成员,如果要运行,就必须得被对象调用)
1、当成员变量和局部变量重名,可以用关键字this区分
class Person
{
private String name;
private int age;
Person(String name)
{
this.name = name;
}
public void speak()
{
System.out.println(this.name+":"+this.age);
}
}
2、this关键字也可以用于在构造函数中调用其他构造函数。
this.方法名称
用来访问本类的成员方法
this();
访问本类的构造方法
()中可以有参数的 如果有参数 就是调用指定的有参构造
注意事项:
1.this() 不能使用在普通方法中 只能写在构造方法中
2.必须是构造方法中的第一条语句
class Person
{
private String name;
private int age;
Person()
{
name = "baby";
age = 1;
System.out.println("Person run");
}
Person(String name)
{
this.name = name;
}
Person(String name,int age)
{
this();
this.name = name;
this.age = age;
}
public void speak()
{
System.out.println(this.name+":"+this.age);
}
}
class ThisDemo
{
public static void main(String[] args)
{
Person p = new Person("小强",10);
p.speak();
}
}