【问题标题】:Cant access object properties java无法访问对象属性java
【发布时间】:2017-05-20 04:30:01
【问题描述】:
List<Employeee> employees = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
String[] input = new String[6];
int n = Integer.valueOf(scanner.nextLine());
for (int i = 0; i < n; i++) {
    input = scanner.nextLine().split(" ");
    employees.add(new Employeee(input[0], Double.parseDouble(input[1]), input[2], input[3], input[4],
            Integer.valueOf(input[5])));
}
for (Object i : employees) {
        System.out.println(i.sallary); //And here ofc idk what to do to print them
        System.out.println(i.name);
}

所以在这里我只是从我的自定义类中制作了几个对象并将它们放在列表中。 之后,我用 for 循环遍历该列表,我想打印它们的属性,但它不允许我这样做。我的 Employeee 类很简单,我什至不会从中粘贴 getter 和 setter。

public class Employeee {

    private String name;
    private double sallary;
    private String possition;
    private String department;
    private String email;
    private int age;

    public Employeee(String name, double sallary, String possition, String department, String email, int age) {
        this.name = name;
        this.sallary = sallary;
        this.possition = possition;
        this.department = department;
        this.email = email;
        this.age = age;
    }
}

【问题讨论】:

  • “它不让我”是什么意思?
  • 另外,sallay 的拼写是不带r 还是拼写错误?
  • 寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定问题或错误必要的最短代码 重现它在问题本身。没有明确问题陈述的问题对其他读者没有用处。请参阅:How to create a Minimal, Complete, and Verifiable example
  • 你提到你的Employeee 类有getter 和setter。你为什么不使用它们来获得你想要的属性?
  • 当然有帮助。当然,它与帖子有所不同。 不要荒谬。

标签: java object properties


【解决方案1】:

这里有很多问题。

  1. 您的属性名称拼写错误。
  2. 您在应该使用Employee 的for-each 语句中使用Object
  3. 您尝试从类外部直接访问的字段被声明为private,这意味着您不能。您应该改用相应的访问器函数。

【讨论】:

    猜你喜欢
    • 2011-07-05
    • 1970-01-01
    • 2016-07-22
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多