public class Person{
private String name;
private int age;
private String gender;
public Person(){
System.out.println("无参数的构造方法");
}
public Person(String name,int age,String gender){
System.out.println("有参数的构造方法");
this.name=name;
this.age=age;
this.gender=gender;
}
}
Teacher类:
public class Teacher extends Person{
private float salary;
public Teacher(){
}
public Teacher(String name,int age,String gender,float salary){
super(name,age,gender);
this.salary=salary;
}
}
当执行下面语句时:
Teacher john=new Teacher("john",34,"male"3000);
会将name,age,gender,salary分别初始化为john,34,male,3000。
若在子类的构造方法没有明确写明调用父类构造方法,则系统会自动调用父类不带参数的构造方法,即执行“super()”。
2.访问父类的属性和方法
除了调用直接父类的构造方法,通过在此类中使用super做前缀外,还可以引用父类中被子类隐藏(即子类中有与父类同名的属性)的属性和被子类覆盖的方法。
public class Person{
private String name;
private int age;
private String gender;
public Person(){
System.out.println("无参数的构造方法");
}
public Person(String name,int age,String gender){
System.out.println("有参数的构造方法");
this.name=name;
this.age=age;
this.gender=gender;
}
public void print(){
//使用super.print()调用父类的print()方法
super.print();
System.out.println("salary:"+salary);
}
}
Teacher类:
public class Teacher extends Person{
private float salary;
public Teacher(){
}
public Teacher(String name,int age,String gender,float salary){
super(name,age,gender);
this.salary=salary;
}
public void print(){
//使用super.print()调用父类的print()方法
super.print();
System.out.println("salary:"+salary);
}
}
Teacher john=new Teacher("john",34,"male",3000);
john.print();
有参数的构造方法
name:john
age:34
gender:male
salary:3000.0
从结果可以看到,在Teacher的print()方法中,通过super.print()调用了父类Person的print()方法,从而输出了name,age,gender属性的内容。