java this的用法

标签:Java


如下写了三个构造器Test(int i)Test(String s)Test(int i, String s),其中第三个构造器以this(i)调用了第一个构造器,并且只能在最开始调用一次,不能再继续调用第二个构造器了。且只有在构造函数里能够用this(.)调用构造器,一般的函数里不能调用构造器(line 9)。

如果传入参数和类属性的名称一样,产生冲突,则用this.xxx来指代类属性。没有冲突的话可以不写this.

public class Test{
    private int i = 0;
    Test(int i) {
        this.i = i + 1;
        System.out.println("parameter:" + i + "  member of Test:" + this.i);
    }
    void pr() {
        System.out.println("print member i:" + i);
        //this(100);  // not constructor, can't call Test(int i)
    }
    Test(String s){
        System.out.println("String s:" + s);
    }
    Test(int i, String s) {
        this(i);     // call Test(int i)
        //this(s);   // can't call twice
        System.out.println("member of Test:" + this.i);
    }
    public static void main(String[] args) {
        Test tt0 = new Test(10);
        tt0.pr();
        Test tt1 = new Test("ok");
        Test tt2 = new Test(20, "ok again!");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值