?? chap8-6.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); // 調(diào)用父類的構(gòu)造函數(shù)
secretaryName="";
}
public manager( ){ } // 默認構(gòu)造函數(shù)
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]; // 定義一個對象數(shù)組
staff[0]=new employee("John",1000,new Date(1994,10,1)); // 雇員對象
manager m=new manager("Smith",1500,new Date(1994,6,12)); // 經(jīng)理對象
staff[2]=new employee("Tony",1000,new Date(1994,4,26)); // 雇員對象
m.setSecretaryName("Anna"); // 設(shè)置經(jīng)理的秘書名
staff[1]=m;
try{
// 創(chuàng)建序列化對象文件
FileOutputStream ostream = new FileOutputStream("test.dat");
ObjectOutputStream out = new ObjectOutputStream(ostream);
out.writeObject(staff);
out.close( );
// 從對象文件中讀取數(shù)據(jù)
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);
}
}
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -