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()方法后的输出

本文详细介绍了Java中的关键字`this`的三种主要用途:1) 区分成员变量和局部变量,2) 调用构造方法和普通方法,3) 作为当前对象的引用。通过实例代码展示了`this`在实际编程中的应用,帮助读者深入理解其功能。
793

被折叠的 条评论
为什么被折叠?



