标签:style blog http color ar 使用 java sp div
先看代码
class Person{
int age;
String name;
Person(){
System.out.println("Person的无参数构造函数");
}
Person(int age,String name){
this.age = age;
this.name = name;
System.out.println("Person的有参数构造函数");
}
void eat(){
System.out.println("吃饭");
}
}
class Student extends Person{
int grade;
Student(){
//super(); 默认添加
System.out.println("Student的无参数构造函数");
}
Student(int age,String name,int grade){
//this.age = age; 与父类中的代码重复
//this.name = name;
super(age,name); //调用父类的构造函数
this.grade = grade;
}
}
class Test{
public static void main(String args[]){
Student s2 = new Student();
Student s1 = new Student(18,"zhangsan",3);
}
}

在子类的构造函数当中,必须调用父类的构造函数。如果子类构造函数里没有明确调用父类的构造函数,编译器会自动添加super(); 根据括号内传入的参数来调用具体的父类构造函数(与this类似)。
为什么??
由于子类继承了父类中的成员变量和成员函数,但无法继承构造函数。在子类的构造函数中给父类的成员变量赋值时必然会产生重复代码,使用super关键字来调用父类中的构造函数解决此问题。
当使用super来调用父类中的构造函数时,这行代码必须是第一条语句。
标签:style blog http color ar 使用 java sp div
原文地址:http://www.cnblogs.com/chavez-wang/p/4052847.html