gpt4 book ai didi

java - 除主方法/类之外的单独类中的数组

转载 作者:行者123 更新时间:2023-12-01 18:38:20 25 4
gpt4 key购买 nike

我不断收到此错误,其原因是数组减速后需要大括号。 enter image description here

我不知道该怎么办。我想创建一个不在我的 main 方法中的数组。我希望数组是用子类填充的父类(super class)型。这是我的代码

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

最佳答案

错误原因如下:

employees[0]= new Manager("Thomas", "Cummings");

因为你不能将可执行语句放在 java 类中的代码块(方法、 block 、构造函数)之外。

解决此问题的一种方法是在构造函数中移动初始化语句:

public class ArrayTest {

Employee [] employees = new Manager[2];

public ArrayTest() {
employees[0]= new Manager("Thomas", "Cummings");
}

}

关于java - 除主方法/类之外的单独类中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20877549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com