[英]How do I resolve wrong output error in java aggregation?
我的代碼運行良好,但在輸出中,兩名員工的地址相同。 為什么會這樣,我該如何解決?
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();
}
}
問題是address
的靜態變量:
class address{
static String country,state,cityname;
...
刪除static
關鍵字。
還將您的屬性設為私有並添加 getter 和 setter。
注意java命名約定。 類名應以大寫字符開頭
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.