【问题标题】:How do I resolve wrong output error in java aggregation?如何解决 java 聚合中的错误输出错误?
【发布时间】:2020-01-18 18:58:31
【问题描述】:

我的代码运行良好,但在输出中,两位员工的地址相同。为什么会这样,我该如何解决?

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();
    }
}

【问题讨论】:

  • 注意 java 命名约定。类名应以大写字符开头
  • 静态变量是个大忌

标签: java class inheritance methods output


【解决方案1】:

问题是address中的静态变量:

class address{
    static String country,state,cityname;
...

删除 static 关键字。

还将您的属性设为私有并添加 getter 和 setter。

注意 java 命名约定。类名应以大写字符开头

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-07
    • 2015-06-01
    • 1970-01-01
    • 2020-10-21
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多