我的代码工作正常,但在输出中,两名员工都有相同的地址。为什么会发生这种情况以及如何解决?
package practice;
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();
}
}
最佳答案
问题出在地址
中的静态变量:
class address{
static String country,state,cityname;
...
删除static
关键字。
同时将您的属性设为私有(private)并添加 getter 和 setter。
注意 Java 命名约定。类名应以大写字符开头
关于java - 如何解决java聚合中的错误输出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59803839/