this关键字
- this是当前对象,this关键字只能在当前类的非静态方法内部使用(非static)。
- this可以看作一个变量,它的值是当前对象的引用。
一、this关键字主要有三个特征应用:
1、thiis调用本类中的属性,也就是类中的成员变量,可以处理方法中成员变量与参数重名的情况。
2、 this调用本类中的其他方法。(例如下面this调用当前对象的方法)
3、this调用本类中的其他构造方法,调用时要放在构造方法的首行。
this重大的作用:返回类的引用(解决参数同名的情况)例如:可以使用return、this放回类的引用。、
public class Demo2 {
public static void main(String[] args) {
Student1 xm = new Student1();
xm.setName("小明");
xm.study();
}
}
class Student1{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;//1.2处理方法中成员变量与参数重名的情况。
}
public void study() {
this.setName("张三");//2、this调用当前对象的方法)
System.out.println(this.name + "正在学习" );
//1.1this调用本类中的属性,也就是类中的成员变量.
}
}