this 关键字
1、大部分时候,普通方法访问其他方法、成员变量时无须使用 this 前缀,但如果方法里有个局部变量和成员变量同名,但程序又需要在该方法里访问这个被覆盖的成员变量,则必须使用 this 前缀。
public class test3 {
private String name="XiaoHon";
public void print1(String name){
System.out.println(name);//输出赋予的参数
System.out.println(this.name);//指向成员变量
}
}
public class test {
public static void main(String[] args) {
test3 t = new test3();
t.print1("helloWorld");
}
}
输出结果
helloWorld
XiaoHon
2、this.方法名 让类中一个方法,访问该类里的另一个方法或实例变量。
public class test {
public static void main(String[] args) {
test2 t = new test2();
t.print2("helloWorld");
}
}
class test2 {//当前类的构造函数
public void print1(){
System.out.println("输出调用当前类的方法print1【无参】");
}
public void print2(String s1){
System.out.println("输出调用当前类的方法print2【带参】"+s1);
this.print1();
}
}
输出结果
输出调用当前类的方法print2【带参】helloWorld
输出调用当前类的方法print1【无参】
3、this():在创建构造方法时,可以用来调用当前类的构造方法。【必须放在构造方法的最前面】
如下:
新建一个test2类,显示定义无参构造函数test(),再定义有参构造函数test2(String s1)。
public class test2 {//当前类的构造函数
public test2() {
System.out.println("输出构造函数【无参】");
}
public test2(String s1) {//构造函数调用当前类的构造函数
this();
System.out.println("输出构造函数【带参】+"+"s1");
}
}
使用test调用test2
public class test {
public static void main(String[] args) {
test2 t = new test2();
test2 t2 = new test2("HelloWorld");
}
}
输出构造函数【无参】
输出构造函数【无参】
输出构造函数【带参】+s1
进程已结束,退出代码 0