一.学习内容
1.继承机制
关键字:extends
2.final修饰符
修饰的类不能被继承,派生子类
修饰的方法不能被重写
修饰的变量不允许修改
3.代码如下:
(1)继承机制
1.Employee.java
import java.util.Date;
import java.util.GregorianCalendar;
/**
* 员工类
* @version v1.0 2018-03-13
* @adthor 叶汉伟
*/
public class Employee {
private String name;
private double salary;
private Date hireDay;
/**
* 构造函数
* @param n 员工姓名
* @param s 员工工资
* @param year 雇佣年份
* @param month 雇佣月份
* @param day 雇佣日
*/
public Employee(String n,double s,int year,int month,int day){
this.name=n;
this.salary=s;
GregorianCalendar calendar=new GregorianCalendar(year,month-1,day);
this.hireDay=calendar.getTime();
}
public String getName(){
return this.name;
}
public double getSalary(){
return this.salary;
}
public Date getHireDay(){
return this.hireDay;
}
public void raiseSalary(double byPercent){
double raise=salary*byPercent/100;
salary+=raise;
}
2.Manager.java
/**
* 经理类,继承了员工类Employee,经理也是员工。
* @version v1.0 2018-03-13
* @author 叶汉伟
*/
public class Manager extends Employee{
private double bonus;
/**
* 构造函数
* @param n 员工姓名
* @param s 员工工资
* @param year 雇佣年份
* @param month 雇佣月份
* @param day 雇佣日
*/
public Manager(String name,double s,int year,int month,int day){
super(name, s, year, month, day);
this.bonus=0;
}
//经理的工资=基本工资+奖金
public double getSalary(){
double baseSalary=super.getSalary();
return baseSalary+bonus;
}
//奖金
public void setBonus(double b){
bonus=b;
}
3.ManagerTest.java
public class ManagerTest {
public static void main(String[] args){
Manager boss=new Manager("Carl Cracker",80000,1987,12,15);
boss.setBonus(5000);
Employee[] staff=new Employee[3];
staff[0]=boss;
staff[1]=new Employee("Harry Hacker",50000,1989,10,1);
staff[2]=new Employee("Tommy Tester",40000,1990,3,15);
for(Employee e:staff)
System.out.println("name:"+e.getName()+",salary="+e.getSalary());
}