http://user.qzone.qq.com/1282179846/blog/1470248763
引入一個簡單的例子:
//Employee類
import java.util.*;
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 = salary*bypercent/100;
salary = salary + raise;
}
//public static void main(String[] args) {
//Employee[] staff = new Employee[3];
//staff[0]=new Employee("diyige",75000,1987,12,25);
//staff[1]=new Employee("dierge",50000,1989,10,1);
//staff[2]= new Employee("disange",40000,1990,3,15);
//for(Employee e : staff)
//{
// e.raisesalary(5);
//}
//for(Employee e : staff)
//{
// System.out.println("name="+e.getName()+",salary="+e.getsalary()+",hireday="+e.gethireday());
//}
//}
}
//manager類
public class Manager extends Employee{
private double bonus;
public Manager(String n,double s,int year,int month,int day)
{
super(n,s,year,month,day);
bonus = 0;
}
public void setbonus(double b)
{
bonus = b;
}
public double getsalary()
{
double basesalary = super.getsalary();
return basesalary+bonus;
}
//public static void main(String[] args) {
//}
}
//Testmanager
public class Testmanager {
public static void main(String[] args) {
Manager boss = new Manager("bossa",80000,1987,12,15);
boss.setbonus(5000);
Employee[] staff = new Employee[3];
staff[0]=boss;
staff[1]= new Employee("diyige",50000,1989,10,1);
staff[2]= new Employee("dierge",40000,1990,3,15);
for(Employee e : staff)
{
System.out.println("name="+e.getName()+",salary="+e.getsalary());
}
}
}
1/關鍵字extends表示繼承。表明正在構造一個新類派生於一個已經存在的類。已經存在的類稱為超類/基類/或者父類;新類稱為子類/派生類/或者孩子類。
子類擁有的功能比超類更加的豐富。(是一句廢話)
在設計的時候要將通用的方法放在超類中,將具有特殊用途的方法放在子類中。
2/子類要想訪問要想訪問超類中的方法需要使用特定的關鍵字super。例如:
public double getsalary()
{
double basesalary = super.getsalary();
return basesalary+bonus;
}
在子類中可以增加域,增加方法,覆蓋超類的方法,然而絕對不能刪除集成的任何域和方法。
3/上面的代碼中,有:
public Manager(String n,double s,int year,int month,int day)
{
super(n,s,year,month,day);
bonus = 0;
}
其中
super(n,s,year,month,day);
的意思是調用超類中含有n,s,year,month,day參數的構造器。由於子類的構造器不能訪問超類中的私有域,所以必須利用超類中的構造器對這部分的私有域進行初始化,我們可以通過super實現對超類構造器的調用。
super調用構造器的語句必須是子類構造器的第一條語句。