构造函数
构造函数跟对象的名字一定相同,主要在对象new时使用,构造函数可以多个,参数不同,且没有返回值;
public class Person {
private String name;
private int age=18;
public Person() {
super();
System.out.println(11);
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
System.out.println(22);
}
}
public class TestPerson {
public static void main(String[] args) {
Person person1=new Person();
Person person2=new Person("张三",28);
}
}
运行结果为:
11
22