构造函数用于初始化,但是并不是所有的构造函数都对外提供,而是只需要提供一些必须要使用者去初始化的构造函数,其它不对外提供的构造函数可以通过this()来调用并初始化。如:
public class Student
{
String name;
int age;
private static int count =0;
private Student() //私有构造方法,不对外提供,每调用一次,count就加1
{
System.out.println("Wellcome!!");
++count;//计算人数
}
public Student(String name,int age)
{
this();//调用无参构造方法Student ( )
this.name = name;
this.age = age;
}
public static void main(String[] args)
{
Student stu1 = new Student("lisi",15);
System.out.println("一共有"+count+"个学生");//count ==1
Student stu2 = new Student("wangwu",15);
System.out.println("一共有"+count+"个学生");//count ==2
}
}
|