private String name;
public Employee(String n,int i){
String name = n;
int id = i;
}
private static int id;
public static void setId(){
id++;
}
public static void main(String args[]){
Employee[] ee =new Employee[3];
ee[0] = new Employee("张三",1000);
ee[1] = new Employee("李四",2000);
ee[2] = new Employee("王五",1800);
for(int i = 0;i<ee.length;i++){
setId();
System.out.println("名字" + ee[i].getName() +" ID=" + ee[i].setId());
}
}
public String getName() {
return getName();
}
public void setName(String name) {
this.name = name;
}
}
╮(╯▽╰)╭。。凌乱了作者: 林志进 时间: 2012-11-1 22:51
完整代码,运行试下吧
class Employees {
private String name;
public String getName() {
return name;
}
private static int id; // static修饰的变量是共享的数据,默认初始为0;
public Employees(String n, int i) {//每调用一次构函,相当于id重新赋值一次
name = n;
id = i;
}
public int getId() {return id;}
public static void setId() {id++;}
public static void main(String args[]) {
Employees[] ee = new Employees[3];
ee[0] = new Employees("张三", 1000);// 第一次赋值后共享数据变成1000
ee[1] = new Employees("李四", 2000);// 第二次赋值后共享数据变成2000
ee[2] = new Employees("王五", 1800);// 第三次赋值后共享数据变成1800
for (int i = 0; i < ee.length; i++) {
setId(); // 循环三次,id进行了三次自增,打印结果 为1801 1802 1803
System.out.println("名字" + ee[i].getName() + " ID=" + ee[i].getId());}
}
}作者: 曾翰翰 时间: 2012-11-1 22:54