|
class person { private string name=""; private int age=0;
public person() { system.out.println("person无参数构造函数"); }
public person(string name,int age) { this.name=name; this.age=age; system.out.println("person 2 参数的构造函数"); } }
class student extends person {
private string school; private string grade;
public student() { system.out.println("student 无参数的构造函数"); }
public student(string name ,int age,string school) { system.out.println("student 3 参数的构造函数"); } public student(string name ,int age,string school,string grade) { super(name,age); this.school=school; this.grade=grade; system.out.println("student 4 参数的构造函数,super()."); } }
class test { public static void main(string [] args) { system.out.println("st1:"); student st2=new student(); system.out.println("---------------------------"); system.out.println("st2:"); student st=new student("zhangshan",76,"武大"); system.out.println("---------------------------"); system.out.println("st3:"); student st3=new student("lisi",24,"武大","研究生");
} } |
/*
=======================================
输出如下:
e:\javawork>java test
st1:
person无参数构造函数
student 无参数的构造函数
---------------------------
st2:
person无参数构造函数
student 3 参数的构造函数
---------------------------
st3:
person 2 参数的构造函数
student 4 参数的构造函数,super().
**************************************
说明了创建一个子类的对象实例的时候,必先调用父类的无参数的构造函数(默认构造函数),假如父类有带参数的构造函数,那么系统将不会给它创建无参数的构造函数,这时,子类在实例化的时候,因为找不到父类的默认构造函数,编译器将会报错,但如果在子类的构造函数中指定用父类的带参数的构造函数的时候,或者在父类中加一个无参数的构造函数,就不会报错。
=============================================
我们假设a是b的父类,b是a的子类。
1、如果程序员没有给类a没有提供构造函数,则编译器会自动提供一个默认的无参数的构造函数,如果用户提供了自己的构造函数,则编译器就不在提供默认的无参数构造函数。
2、子类b实例化时会自动调用父类a的默认构造函数,所以如果a的默认的无参数的构造函数为private,则编译器会报错,而如果a没有提供默认的无参数的构造函数,而提供了其他类型的构造函数,编译器同样会报错,因为b找不到a的默认无参数构造函数。所以,我们最好给父类a提供一个无参数的构造函数。
3、或者在b的构造函数中显示的调用父类a的有参构造函数。super(parameter)