Java构造函数

package test;

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 Student1 extends Person

{

private String school;

private String grade;

public Student1()

{

System.out.println("student 无参数的构造函数");

}

public Student1(String name ,int age,String school)

{

System.out.println("student 3 参数的构造函数");

}

public Student1(String name ,int age,String school,String grade)

{

super(name,age);

this.school=school;
this.grade=grade;

System.out.println("student 4 参数的构造函数,super().");

}

}

class estend

{

public static void main(String [] args)

{

System.out.println("st1:");

Student1 st2=new Student1();

System.out.println("---------------------------");

System.out.println("st2:");

Student1 st=new Student1("zhangshan",76,"武大");

System.out.println("---------------------------");

System.out.println("st3:");

Student1 st3=new Student1("lisi",24,"武大","研究生");

}

}

   说明了创建一个子类的对象实例的时候,必先调用父类的无参数的构造函数(默认构造函数),假如父类有带参数的构造函数,那么系统将不会给它创建无参数的构造函数,这时,子类在实例化的时候,因为找不到父类的默认构造函数,编译器将会报错,但如果在子类的构造函数中指定用父类的带参数的构造函数的时候,或者在父类中加一个无参数的构造函数,就不会报错。

=============================================

我们假设AB的父类,BA的子类。

1
、如果程序员没有给类A没有提供构造函数,则编译器会自动提供一个默认的无参数的构造函数,如果用户提供了自己的构造函数,则编译器就不在提供默认的无参数构造函数。

2
、子类B实例化时会自动调用父类A的默认构造函数,所以如果A的默认的无参数的构造函数为private,则编译器会报错,而如果A没有提供默认的无参数的构造函数,而提供了其他类型的构造函数,编译器同样会报错,因为B找不到A的默认无参数构造函数。所以,我们最好给父类A提供一个无参数的构造函数。

3、或者在B的构造函数中显示的调用父类A的有参构造函数。superparameter

原文地址:https://www.cnblogs.com/pengfeiliu/p/3722381.html