我一直收到这个错误,它是关于在数组解除后需要括号的。
我不知道该怎么做。我想创建一个不在我的main方法中的数组。我希望数组是用子类填充的超类型。 这是我的代码
public class ArrayTest {
Employee [] employees = new Manager[2];
employees[0]= new Manager("Thomas", "Cummings");
}
public class Manager extends Employee{
private int employees;
public Manager() {
super();
employees = 0;
}
public Manager(int employees) {
super();
this.employees = employees;
}
public Manager(String f_name, String l_name) {
super(f_name, l_name);
}
public Manager(String f_name, String l_name, int employees) {
super(f_name, l_name);
this.employees = employees;
}
public int getEmployees() {
return employees;
}
public void setEmployees(int employees) {
this.employees = employees;
}
public void setManager(String f_name, String l_name){
this.setF_name(f_name);
this.setL_name(l_name);
}
public void setManager(String f_name, String l_name, int employees){
this.setF_name(f_name);
this.setL_name(l_name);
this.employees = employees;
}
@Override
public String toString(){
return "\nName " + getF_name() + " " + getL_name() +
"\nEmployee ID " + getEmp_id() +
"\nNum of employees " + getEmployees();
}
}
public class Employee {
private String f_name, l_name;
private static long emp_id = 001;
public Employee(){
f_name = "";
l_name = "";
emp_id ++;
}
public Employee(String f_name, String l_name) {
this.f_name = f_name;
this.l_name = l_name;
emp_id ++;
}
public String getF_name() {
return f_name;
}
public void setF_name(String f_name) {
this.f_name = f_name;
}
public String getL_name() {
return l_name;
}
public void setL_name(String l_name) {
this.l_name = l_name;
}
public long getEmp_id() {
return emp_id;
}
public void setEmp_id(long emp_id) {
Employee.emp_id = emp_id;
}
public String toString(){
return "\nName " + getF_name() + " " + getL_name() +
"\nEmployee ID " + getEmp_id();
}
}
答案 0 :(得分:3)
错误的原因如下:
employees[0]= new Manager("Thomas", "Cummings");
因为你不能将可执行语句放在代码块(方法,块,构造函数)之外的java类中。
解决此问题的一种方法是在构造函数中移动初始化语句:
public class ArrayTest {
Employee [] employees = new Manager[2];
public ArrayTest() {
employees[0]= new Manager("Thomas", "Cummings");
}
}
答案 1 :(得分:1)
employees[0]= new Manager("Thomas", "Cummings");
这是一个需要放在适当的可执行块(方法,构造函数,初始化块)中的语句