NullPointerException when working with arrays

后端 未结 3 539
感情败类
感情败类 2021-01-14 22:41

I am trying to create a program for an online Java course. This program includes an Employee class and a Name class. I have to create multiple Employee objects and prompt th

3条回答
  •  不思量自难忘°
    2021-01-14 23:11

    You're not creating any Employee objects. Creating the array doesn't create any Employee objects - the array doesn't contain objects, it contains references, and initially all those references are null. You just need:

    employee[j] = new Employee();
    employee[j].setFirstName(nameF);
    

    It's worth being very clear about the differences between objects and references - it affects all aspects of the language, from default values, to the assignment operator, to parameter passing, to garbage collection. It can be particularly confusing if you've come from a C++ background, I believe.

提交回复
热议问题