一、this.属性名
当一个类的属性(成员变量)名与访问该属性的方法参数名相同时,则需要使用 this 关键字来访问类中的属性,以区分类的属性和方法中的参数。
public class Teacher {
//声明类的成员变量(属性)
private String name;
private double salary;
private int age;
//有参构造方法
public Teacher(String name,double salary,int age){
this.name = name;
this.salary = salary;
this.age = age;
}
public static void main(String[] args) {
Teacher teacher = new Teacher("Yale", 10000, 24);
System.out.println("The only phd teacher: ");
System.out.println("Name:"+teacher.name+
"\nSalary:"+teacher.salary+
"\nAge:"+teacher.age);
}
二、this.方法名
某个方法调用同一类中别的方法,不需要再创建对象,直接用this。
public class Dog {
//jump方法
public void jump(){
System.out.println("JumpJumpJump");
}
//run方法
public void run(){
this.jump();
System.out.println("run() had called jump().");
}
public static void main(String[] args) {
Dog dog = new Dog();
dog.run();
}
三、this()访问构造方法
使用 this( ) 在构造方法中给 name 赋值。
public class Student {
String name;
//无参构造方法,使用 this( ) 在构造方法中给 name 赋值
public Student(){
this("Slender");
}
//有参构造方法
public Student(String name){
this.name = name;
}
//输出信息
public void print(){
System.out.println("Name:"+name);
}
public static void main(String[] args) {
Student student = new Student();
student.print();
}
}