/*
构造方法:构造器
作用:建立对象的时候,对类中成员变量初始化,
1.构造方法的名字必须与类的名字相同
2.构造方法没有返回值
3.没有return
4.调用对象的时候直接调用构造方法,不需要再次调用
5.创建对象的时候,仅运行一次this()
1.可以再构造方法之间调用
2.调用构造方法,参数列表
3.this必须写在构造方法的第一行*/
class People2{private String name;private int age;//构造方法对成员变量进行初始化赋值(用户传参)People2(String name,int age){this.name = name;this.age = age;}//方法重载,名相同,参数不一致(用户不传参)People2(){this.name = "张三";this.age = 20;}People2(String name){this(name,18); }People2(int age){this("王二",age);}public void speak(){System.out.println(this.name+this.age);}
}public class ConstructorDemo {public static void main(String[] args) {//用户传参People2 p = new People2("李四",20);p.speak();//用户不传参数People2 pe = new People2();pe.speak();//用户值传递一个参数People2 P1 = new People2("王文");P1.speak();}
}