Java Constructor



class ConstructorTry {
    public static void main(String[] args) {
        ConstructorTry02 cons01 = new ConstructorTry02("lord");
        System.out.println(cons01.name);
        System.out.println(cons01.age);
        System.out.println("**********");

        ConstructorTry02 cons02 = new ConstructorTry02(18);
        System.out.println(cons02.name);
        System.out.println(cons02.age);
        System.out.println("**********");

        ConstructorTry02 cons03 = new ConstructorTry02("lord", 18);
        System.out.println(cons03.name);
        System.out.println(cons03.age);
        System.out.println("**********");

        ConstructorTry02 cons04 = new ConstructorTry02();
        System.out.println(cons04.name);
        System.out.println(cons04.age);
        System.out.println("**********");
    /*
    lord
    -1
    **********
    anoymous
    18
    **********
    lord
    18
    **********
    anoymous
    -1
    **********  
    */
    }
}
class ConstructorTry02 {
    String name;
    int age;
    ConstructorTry02(String name, int age){
        this.name = name;
        this.age = age;
    }
    ConstructorTry02(int age){
        this("anoymous", age);
    }
    ConstructorTry02(String name){
        this(name, -1);
    }
    ConstructorTry02(){
        this("anoymous", -1);
    }
}

你可能感兴趣的:(Java Constructor)