Sh0*_*gun 4 java arrays inheritance initialization
所以我正在搞乱无意识和多态性.一切都很顺利,直到我到达测试人员,我必须做一个类型员工(我的超级班)的数组.目前尝试运行此程序给我这个错误.
线程"main"java.lang.NullPointerException中的异常
我假设这与我声明我有employeeArray = null;时有关.但是把它留下来我把每个员工都放到数组中会出错,它说必须启动员工数组,默认情况下通过包含employeeArray = null;来实现.我在java上的这本书并没有真正触及这些类型的数组,而且我一直无法在网上找到麻烦的答案.任何人都可以提供任何帮助将不胜感激.
我也试过这样的事
Employee [] employeeArray = new Employee[3] ;
Run Code Online (Sandbox Code Playgroud)
这没有返回任何错误,但没有返回我正在寻找的东西.这更像我的需要,但我的超级和子类有问题吗?
public class EmployeeTest {
public static void main(String[] args){
Employee [] employeeArray = null;
SalariedEmployee employee1 = new SalariedEmployee("Esther", "Smith", "111-111-111", 6, 2011, 2400);
CommissionedEmployee employee2 = new CommissionedEmployee("Nick", "McRae", "222-222-222", 1, 1998, 50000, 0.1);
SalPlusCommEmployee employee3 = new SalPlusCommEmployee("Dan", "Mills", "333-333-333", 3, 2011, 1000, 0.05, 500 );
employeeArray[0] = employee1;
employeeArray[1] = employee2;
employeeArray[2] = employee3;
System.out.println(employeeArray[0].getEmployeeDetails);
System.out.println(employee1.toString()); // call the method from the sub class SalariedEmployee
System.out.println(employee2.toString()); // call the method from the sub class CommissionedEmployee
System.out.println(employee3.toString()); // call the method from the sub class SalPlusCommEmployee
}
Run Code Online (Sandbox Code Playgroud)
你需要使用
Employee [] employeeArray = new Employee[3];
以及在末尾添加括号 employeeArray[0].getEmployeeDetails()
但在你的情况下,你不需要担心使用数组并给它一个大小,你可以使用一个ArrayList代替,如下所示:
ArrayList<Employee> employees = new ArrayList<Employee>();
employees.add(new SalariedEmployee(...));
employees.add(new CommissionnedEmployee(...));
...
Run Code Online (Sandbox Code Playgroud)
至于调用toString()上的员工,你需要属性重写的toString()Employee类,以任何你想要的输出中是方法,否则你会得到默认toString()的的Object类,它输出的类名和哈希的十六进制表示对象的代码.
你的Employee类应该有这个方法(类似的东西):
public String toString() {
return this.name + " " + this.firstName ...;
}
Run Code Online (Sandbox Code Playgroud)