简述关键字this
一、this代表对当前对象的一个引用。
public class Student {
String name;
public void study()
{
System.out.println(this);//对当前对象的引用。
}
public static void main(String[] args)
{
Student student=new Student();
student.study();
System.out.println(student);
}
}
Student@52e922
Student@52e922
二、this关键字用于调用属性、方法及本类中构造方法。
1.调用属性:
public class Student {
String name;
public void study()
{
System.out.println(this.name+"正在学习...");//用于调用属性。
}
public static void main(String[] args)
{
Student student=new Student();
student.study();
}
}
输出:
null正在学习…、
2.调用本类中构造方法:
public class Student {
int age;
String name;
public Student(int age) {
this.age = age;
}
public Student(String name) {
this.name = name;
}
public Student(int age, String name) {
this(age);//调用构造方法。
new Student(name);
}
public static void main(String[] args) {
new Student(12, "王五");
}
}