用户自定义类——以雇员工资系统为例
- 自定义类
以工资系统的java实现为例
一个源文件只能有一个公共类,但可以有无数个非公共类,但文件名必须与public类的名字相匹配
public表示可以被任何方法调用,private表示只有Employee类的方法可以访问这些实例字段
import java.time.*;
public class EmployeeTest {
public static void main(String[] args) {
Employee[] staff = new Employee[3];
staff[0] = new Employee( "Carl Cracker", 75000, 1987, 12, 15 );
staff[1] = new Employee( "Harry Hacker", 50000, 1989, 10, 1 );
staff[2] = new Employee( "Tony Tester", 40000, 1990, 3, 15 );
for(Employee e:staff) e.raiseSalary( 5 );
for(Employee e:staff) System.out.println("name = "+ e.getName() + ",salary = " + e.getSalary());
}
}
class Employee{
private String name;
private double salary;
private LocalDate hireDay;
public Employee(String n,double s,int year,int month,int day){
name = n;
salary = s;
hireDay = LocalDate.of( year,month,day );
}
public String getName() { return name; }
public double getSalary() { return salary; }
public LocalDate getHireDay() { return hireDay; }
public void raiseSalary(double byPercent){
double raise = salary*byPercent/100;
salary += raise;
}
}
- 若将每个源文件储存在单独的类中,调用Employee类的代码如下
java Employee*.java