this关键字(3种方法)

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
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值