JAVA base (constructor overloads)

1, overloading:

  • The same method name, has nothing to do with the return value type (constructor does not return value), but only the parameter list

2, the constructor overloads

Notes [1]

  • If we do not give construction method, the system will automatically provide a no-argument constructor method.

  • If we give the construction method, the system will no longer provide a default constructor with no arguments.

    • Note: This time, if we want to use the no-argument constructor, you must give yourself. Recommend never give their no-argument constructor

        

[2] Case

class Demo2_Person {

    public static void main(String[] args) {

        Person p1 = new Person();

        p1.show();





        System.out.println("---------------------");





        Person p2 = new Person("张三",23);

        p2.show();





        System.out.println("---------------------");





        Person p3 = new Person("李四",24);

        p3.show();

    }

}



class Person {

    private String name;            //姓名

    private int age;                //年龄





    public Person() {                //空参构造

        System.out.println("空参的构造");

    }





    public Person(String name,int age) {

        this.name = name;

        this.age = age;

        System.out.println("有参的构造");

    }

    

    public void show() {

        System.out.println(name + "..." + age);

    }

}

 

Guess you like

Origin blog.csdn.net/Cricket_7/article/details/91778971