this关键字代码详解

this关键字代码演示

public class Flower {
    int petalCount = 0;
    String s = "initial value";

    Flower(int petals) {
        petalCount = petals;
        System.out.println("Constructor w/ int arg only,petalCount = " + petalCount);
    }

    Flower(String ss) {
        System.out.println("Constructor w/ String arg only,s = " + ss);
        s = ss;
    }

    /**
     * 尽管可以用this调用一个构造器,但却不能调用两个。此外,必须将构造器调用于最起始处,否则编译器会报错。
     * @param s
     * @param petals
     */
    Flower(String s, int petals) {
        this(petals);
        // 调用“this()”必须是构造体中的第一个语句。
        // this(s);
        // 消除参数歧义;this.s代表数据成员
        this.s = s;
        System.out.println("String & int arg");
    }

    /**
     * 默认无参构造器
     */
    Flower() {
        this("hi", 47);
        System.out.println("default constructor (no args)");
    }

    void printPetalCount() {
        // 不在非构造函数里面
        // this(11);
        System.out.println("petalCount = " + petalCount + " s = " + s);
    }

    public static void main(String[] args){
        Flower x = new Flower();
        x.printPetalCount();
    }
}

代码输出

Constructor w/ int arg only,petalCount = 47
String & int arg
default constructor (no args)
petalCount = 47 s = hi
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值