super 关键字的作用有两个:
1)在子类中调用超类的构造器,完成实例域参数的初始化,调用构造器的语句只能作为另一个构造器(通常指的是子类构造器)的第一条语句出现,
2)在子类中调用超类的方法,如:子类需要覆盖超类中的A方法,但同时也需要调用超类的A方法,故在子类的A方法中调用超类的原有A方法时即可用“super.A”形式完成调用。
import java.util.Date;
import java.util.GregorianCalendar;
\\创建超类Employee
public class Employee{
\\创建实例域
private String name;
private double salary;
private Date hireDay;
\\创建构造器
public Employee(String n,double s,int year,int month,int day){
name=n;
salary=s;
GregorianCalendar calendar=new GregorianCalendar(year.month-1,day);
hireDay=calendar.getTime();
}
\\创建域访问器和更改器方法
public String getName(){
return name;
}
public double getSalary(){
return salary;
}
public Date getHireDay(){
return hireDay;
}
public void raiseSalary(double byPercent){
double raise=raise*byPercent/100;
salary+=raise;
}
}
\\创建子类Manager
public class Manager extends Employee{
private double bouns;
/**
*使用super关键字在子类中调用超类的方法
*
*/
public Manager(String n,double s,int year,int month,int day){
super(n,s,year,month,day);//调用超类的构造器
bouns=0;
}
public double getSalary()/*覆盖超类的getSalary()方法*/
{
double baseSalary=super.getSalary();//调用超类的getSalary()方法
return bouns+baseSalary;
}
public void setBouns(double a){
bouns=a;
}
}