前言
之前的例子中,我们已经编写了一些简单的类。但是,那些类都只包含一个简单的main方法。现在来学习如何编写复杂应用程序所需要的那种主力类。通常这些类没有main方法,却有自己的实例字段和实例方法。要想构建一个完整的程序,会结合使用多个类,其中只有一个类有main方法。
自定义简单的类
在Java中,最简单的类定义形式为:
class ClassName {
// 字段
field1
field2
...
// 构造方法
constructor1
constructor2
...
// 普通方法
method1
method2
...
}
接下来将上面的伪代码填充完整
class Employee {
private String name;
private double salary;
private LocalDate hireDay;
// constructor
public Emploee(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;
}
}
上面就是我们定义的一个普通的类,分为3个部分,变量 + 构造器 + 方法,下面我们编写一个完整的程序,最后输出员工的名字、薪水和出生日期
文件:EmployeeTest/EmployeeTest.java
import java.time.LocalDate;
public class EmployeeTest {
public static void main(String[] args) {
Employee[] staff = new Employee[3];
staff[0] = new Employee("jkc1", 75000, 1987, 12, 15);
staff[1] = new Employee("jkc2", 50000, 1987, 10, 1);
staff[2] = new Employee("jkc3", 40000, 1990, 3, 15);
for (Employee e: staff) {
e.raiseSalary(5);
}
for (Employee e: staff) {
System.out.println("name=" + e.getName() + ", salary=" + e.getSalary() + ", hireDay=" + e.getHireDay());
}
}
}
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
数组,并填入了3个Employee对象:
Employee[] staff = new Employee[3];
staff[0] = new Employee("jkc1", 75000, 1987, 12, 15);
staff[1] = new Employee("jkc2