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

猜你喜欢

转载自blog.csdn.net/qq_33704186/article/details/82316179