super关键字

继承在面向对象的过程中可以说是司空见惯,在实例化子类的时候默认的是先调用父类的无参的构造函数,但在特定的时候这样子是会出错的:
父类: class Person
{
private String name;
private int age;
public void setName(String name){
this.name = name;
}
public void setAge(int age){
this.age = age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
public Person( String name,int age){//有两个参数的构造函数
this.name = name;
this.age = age;
}
}

子类: class Student extends Person
{
private String school;
public Student (String name,int age,String school){//有三个参数的构造函数
this.school = school;
}
public String getSchool(){
return school;
}
}

主类: public class Demo1
{
public static void main(String args[]){
Student stu = new Student("songjindian",24,"nyist");
System.out.println("姓名:"+stu.getName()+";年龄:"+stu.getAge()+";学校:"+stu.getSchool());
}

}

在class Demo中实例化Student时,要调用父类的无参的构造函数,编译出错如下:
Demo1.java:25: 找不到符号
符号: 构造函数 Person()
位置: 类 Person
        public Student (String name,int age,String school){
                                                          ^
1 错误

此时该怎么办呢?好嘚关键字super的出现先,先将Student类的代码改变如下:
class Student extends Person
{
private String school;
public Student (String name,int age,String school){
super(name,age);//在实例化子类是默认是要调用子类的构造方法,但此时没有,必须用super关键字在子类的构造函数中调用
//父类已存在的构造函数
this.school = school;
}
public String getSchool(){
return school;
}
}

再次编译成功,运行:
E:\java\java SE\4-11>javac Demo1.java

E:\java\java SE\4-11>java Demo1
姓名:songjindian;年龄:24;学校:nyist

将自己的学习心得记下!

你可能感兴趣的:(java)