this关键字特点
- 当在方法内需要调用到该方法的对象时就可以用this
- this可以看做是一个变量,他的值是当前对象的引用
- 使用this可以处理方法中的成员变量和形参同名的问题
- 在类的构造方法中可以调用this([参数列表])来调用该类的指定构造方法
示例
- 特点1
package demo;
class Student
{
private int age;
Student(int finalAge)
{
age = finalAge;
}
void getAge()
{
System.out.println("age="+this.age);
}
}
public class Test {
public static void main(String[] args) {
Student t1 = new Student(10);
t1.getAge();
}
}
- 特点2
package demo;
class Student
{
private int age;
Student(int finalAge)
{
age = finalAge;
}
void getAge()
{
Student tmp = null;
tmp = this;
System.out.println("age="+tmp.age);
}
}
public class Test {
public static void main(String[] args) {
Student t1 = new Student(10);
t1.getAge();
}
}
- 特点3
package demo;
class Student
{
private int age;
Student(int age)
{
this.age = age;
}
void getAge()
{
System.out.println("age="+age);
}
}
public class Test {
public static void main(String[] args) {
Student t1 = new Student(10);
t1.getAge();
}
}
- 特点4
this调用语句必须在其他语句之前
package demo;
class Student
{
private int age;
Student(int finalAge)
{
age = finalAge;
}
Student()
{
this(10);
System.out.println("age="+age);
}
}
public class Test {
public static void main(String[] args) {
Student t1 = new Student();
}
}
输出结果均是