在构造器中调用构造器

2019-07-14  本文已影响0人  云烟渐成雨
public class Flower {
    int petalCount = 0;
    String s = "initial value";

    Flower(int petals) {
        petalCount = petals;
        System.out.println("Constructor petalCount = " + petalCount);
    }

    Flower(String ss) {
        System.out.println("Constructor s = " + ss);
        s = ss;
    }

    Flower(String s, int petals) {
        this(petals);
//        this(s);
        this.s = s;
    }

    Flower() {
        this("hi", 47);
    }

    void printPetalCount() {
//        this(11);   除构造器外,编辑器禁止在其他任何方法中调用构造器
        System.out.println("s = " + s +"\n"+ "petalCount = " + petalCount);

    }

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

运行结果:

Constructor petalCount = 47
s = hi
petalCount = 47

构造器Flower(String s, int petals) 表明:尽管可以用this调用一个构造器,但却不能调用两个。此外,必须将构造器调用置于最起位置,否则编译器会报错。

上一篇下一篇

猜你喜欢

热点阅读