静的メソッドと静的フィールド
1772 ワード
package test;
public class StaticTest {
public static void main(String[] args) {
// fill the staff array with three Employee objects
Employee[] staff = new Employee[3];
staff[0] = new Employee("Tom",40000);
staff[1] = new Employee("Dick",50000);
staff[2] = new Employee("Harry",60000);
// print out information about all employee objects
for (int i = 0; i < staff.length; i++)
{
Employee e = staff[i];
e.setId();
System.out.println("name=" + e.getName() + ", id=" + e.getId() +
", salary=" + e.getSalary());
}
int n = Employee.getNextId();
System.out.println("Next available id=" + n);
}
}
class Employee
{
private String name;
private double salary;
private int id;
// , 。 。
private static int nextId = 1;
public Employee(String n,double s){
name = n;
salary =s;
id = 0;
}
public String getName()
{
return name;
}
public void setName(String name){
this.name = name;
}
public double getSalary(){
return salary;
}
public void setSalary(double salary){
this.salary = salary;
}
public int getId(){
return id;
}
public void setId()
{
// set id to next avilable id
id = nextId;
nextId++;
}
// , , 。
public static int getNextId()
{
return nextId; //return static field
}
public static void main(String[] args){
Employee e = new Employee("Harry",50000);
System.out.println(e.getName() + "\t" + e.getSalary());
}
}
実行結果:
name=Tom, id=1, salary=40000.0
name=Dick, id=2, salary=50000.0
name=Harry, id=3, salary=60000.0
Next available id=4