我的代码运行正常,但是在输出中,两个员工的地址都相同。为什么会这样,我该如何解决?包装实践;
class address{
static String country,state,cityname;
public address(String country, String state, String cityname) {
this.country=country;
this.state=state;
this.cityname=cityname;
}
}
class employee{
String name;
int id;
int age;
address add;
public employee(String name, int id, int age,address add) {
this.name=name;
this.id=id;
this.age=age;
this.add=add;
}
void display() {
System.out.println(name+" "+id+" "+age);
System.out.println("the employee stays at"+ address.country+" "+
address.state+" "+address.cityname);
}
}
public class Document {
public static void main(String[] args) {
// TODO Auto-generated method stub
address a2 = new address("A","B","C");
address a1 = new address("D","E","F");
employee e1 = new employee("lmn",123,20,a2);
employee e2 = new employee("pqr", 456,24,a1);
e1.display();
e2.display();
}
}
问题是address
中的静态变量:
class address{
static String country,state,cityname;
...
删除static
关键字。
也将您的属性设为私有并添加getter和setter。
请注意Java命名约定。类名应以大写字母字符>>开头