⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 chap8-6.txt

📁 JAVA 学习资源
💻 TXT
字号:
// 程序8-6
import java.io.*;
import java.util.*;

class employee implements Serializable{ 		// Serializable是一个接口
    private String name;			// 姓名
    private double salary;			// 薪水
    private Date hireDate;			// 雇佣日期

    public employee(String n,double s,Date d){
        name=n;
        salary=s;
        hireDate=d;
    }	

    public employee( ){    }
    
    public void raiseSalary(double percent){
        salary *= 1 + percent/100 ;
    }
    
    public int hireYear( ){			// 获取雇佣年份
        return hireDate.getYear( );
    }
    
    public String getInfo( ){			// 获取雇员的信息
        return name+"\t"+salary+"\t"+hireYear( );
    }
}

class manager extends employee{		// 定义manager类
    private String secretaryName;			// 增加的实例变量secretaryName
    
    public manager(String n,double s,Date d){
        super(n,s,d);				// 调用父类的构造函数
        secretaryName="";		
    }
    
    public manager( ){     }			// 默认构造函数
    
    public void raiseSalary(double percent){
        Date today=new Date(2004,1,12);   
        double honus=0.5*(today.getYear( )-hireYear( ));
        
        super.raiseSalary( honus + percent ) ;
    }

    public void setSecretaryName(String n){
        secretaryName=n;
    }
    
    public String getSecretaryName( ){
        return secretaryName;
    }	
    
    public String getInfo( ){		// 该方法覆盖了父类中的同名方法
        return super.getInfo( )+"\t"+secretaryName;
    }
}

public class objectTest {	
    public static void main(String args[ ]){
        employee staff[ ]=new employee[3]; 	// 定义一个对象数组
        
        staff[0]=new employee("John",1000,new Date(1994,10,1));		// 雇员对象
        manager m=new manager("Smith",1500,new Date(1994,6,12));	// 经理对象
        staff[2]=new employee("Tony",1000,new Date(1994,4,26));	// 雇员对象
        m.setSecretaryName("Anna");     	// 设置经理的秘书名
        staff[1]=m;	
        
        try{
                // 创建序列化对象文件
            FileOutputStream  ostream = new FileOutputStream("test.dat");
            ObjectOutputStream  out = new ObjectOutputStream(ostream);
            out.writeObject(staff);
            out.close( );

                // 从对象文件中读取数据
            FileInputStream  istream = new FileInputStream("test.dat");
            ObjectInputStream  in = new ObjectInputStream(istream); 
            employee newStaff[ ]=(employee[ ]) in.readObject( );         // 读取对象
            
            for(int i=0;i<newStaff.length;i++)
                newStaff[i].raiseSalary(50);			// 工资增加50%
            for(int i=0;i<newStaff.length;i++)
                System.out.println(newStaff[i].getInfo( ));		
             
            in.close( );
        }catch(Exception e) {
            System.out.println("Exception : "+e);
            e.printStackTrace( );
            System.exit(0);
        }
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -