java--在构造函数中调用其他构造函数

使用 this 关键字

public class Flower {
    int petalCount = 0;
    String s = "cyl is qingliu";
    Flower(int petals){
        System.out.println("int");
        petalCount = petals;
    }
    
    Flower(String ss){
        System.out.println("String  :s = " +ss);
        s = ss;
        
    }
    
    Flower(String s,int petals){
        this(petals);//调用其他的构造函数,不能同时调用两个
        this.s = s;
        System.out.println("String && int ");
        
        
    }
    
    Flower(){
        this("hi",47);
        System.out.println("null");
    }
    void printPetalCount(){
        //不能再非构造函数中使用this调用构造函数
        System.out.println("petalCount = " + petalCount + "s = " + s);
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Flower x = new Flower();
        x.printPetalCount();
    }

}


结果展示:

java--在构造函数中调用其他构造函数_第1张图片

你可能感兴趣的:(java日常)