this是Java中常用的关键字
功能详解
1.调用类中属性(this.属性)
当局部变量和成员变量重名时,就需要用this关键字进行区分
public Student(int sid, String name) {
this.sid = sid;//this.sid是成员属性
this.name = name;//成员变量和局部变量重名,就需要用this来区分二者了
}
2.调用类中的普通方法和构造方法(this.方法名()、this())
this()调用构造方法,且只能放在构造方法的第一句
public Student(String name) {
this.name = name;
}
public Student(int sid, String name) {
this(name);//调用的构造方法为public Student(String name)
this.sid = sid;
// this.name = name;
}
this.方法名;调用普通方法
public int number10() {
return this.changeNum();
}
public int changeNum() {
return 10;
}
3.表示当前对象的引用
public Student getCurrent() {
return this;
}
public static void main(String[] args) {
Student s = new Student(9,"tom");
System.out.println(s.getCurrent());
}
运行结果:
注意:这是重写了toString()方法后的输出