Person p = newPerson();
生成对像时,new后面的即为构造函数.
1.构造函数名必须与类名相同,构造函数可以重载.
2.类中没有构造函数,在生成对像时,系统会自动生成一个无参且函数体为空的构造函数.
3.构造函数重载时,调用构造函数时,必須放在函数体的第一行.
//eg:
class Person{
String name;
int age;
Person(String name){
this.name = name;
}
Person(String name,int age){
this(name);
this.age = age;
}
}
4.在调用子类构造函数时,系统会黙认先调用父类的构造函数.当父类构造函数不为空(无参空函数体)时,子类
eg:
class Person{
String name;
int age;
Person(){
System.out.println("父类构造函数.")
}
}
class Student extends Person{
}
class Test {
public static void main(String[] args){
Student s = new Student();
}
}