07-05
17

继承样例 ManagerTest

闲来无事,做了些书上的小练习,把值得注意的地方都写上注视

import java.util.Date;
import java.util.GregorianCalendar;

public class ManagerTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO 自动生成方法存根
        Manager boss=new Manager("Carl Cracker",80000,1987,12,15);
        boss.setBonus(5000);
        
        Employee[] staff=new Employee[3];
        
        staff[0]=boss;
        Employee emp1=new Employee("hacker",50000,1989,10,1);
        emp1.raiseSalary(10); //自行修改样例,员工hacker加入另行工资计算
        staff[1]=emp1;
        staff[2]=new Employee("tester",40000,1990,3,15);
        

                                          //if(staff[1] instanceof Manager)
        //boss=(Manager) staff[1];
        

        for(Employee e:staff)
            System.out.println("name="+e.getName()+",salary="+e.getSalary());

    }

}

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 calenday = new GregorianCalendar(year, month - 1, day);//日历生成
        hireday = calenday.getTime();
    }

    public Date getHireday() {
        return hireday;
    }

    public String getName() {
        return name;
    }

    public double getSalary() {
        return salary;
    }

    public void raiseSalary(double byPercent) {
        double raise = salary * byPercent / 100;
        salary += raise;
    }
    

}

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 double getSalary()
    {
        double baseSalary=super.getSalary();
        return baseSalary+bonus;
    }
    public void setBonus(double b)
    {
        bonus=b;
    }

}

PS:如果单单加入boss=(Manager) staff[1];强制类型转化成Manager类型,那么会报ClassCastException异常;在前面加入if(staff[1] instanceof Manager) ,由instanceof运算符来效验一下,如果不是,自动自动终止跳过。

文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags: Java核心技术
相关日志:
评论: 0 | 引用: 0 | 查看次数: 750
发表评论
昵 称:
密 码: 游客发言不需要密码.
内 容:
验证码: 验证码
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.
字数限制 1000 字 | UBB代码 开启 | [img]标签 关闭