java - 扩展类对象java的ID自动递增
问题描述
有问题,我的 ID 自动递增代码不起作用。对象的 ID 始终为 0。也许有人可以帮我解决这个问题。尝试了不同的方法,但仍然不适合我。对于我的情况,我应该使用 Employee 类作为 ID 计数器。但我不确定我做的是否正确。
超类
public class Person {
public String PersonName;
public String PersonSurname;
public Person()
{
this.PersonName = "";
this.PersonSurname = "";
}
public Person(String PersonName, String PersonSurname)
{
this.PersonName = PersonName;
this.PersonSurname = PersonSurname;
}
@Override
public String toString()
{
return "Person name, surname: "+ this.PersonName + " " + this.PersonSurname;
}
public void setPersonName(String PersonName)
{
this.PersonName = PersonName;
}
public void setPersonSurname(String PersonSurname)
{
this.PersonSurname = PersonSurname;
}
public String getPersonName()
{
return PersonName;
}
public String getPersonSurname()
{
return PersonSurname;
}
带身份证的班级
public class Employee extends Person {
private int EmployeeID;
private static int IdCounter = 0;
public Employee(){
super("","");
EmployeeID = 0;
this.EmployeeID = IdCounter++;
}
public Employee(int EmployeeID, String PersonName, String PersonSurname){
super(PersonName,PersonSurname);
this.EmployeeID = IdCounter++;
}
@Override
public String toString()
{
return "Person name, surname: " +this.EmployeeID + ". " + this.PersonName + " " + this.PersonSurname;
}
public void setEmployeeID(int EmployeeID)
{
this.EmployeeID = EmployeeID;
}
public int getEmployeeID()
{
return EmployeeID;
}
}
我的主要课程
public class Main {
public static void main(String[] rez) {
Scanner scanner = new Scanner(System.in);
String firstDigit = "";
String secDigit = "";
Employee CompanyEmployee = new Employee();
do {
System.out.println("Please input Name: ");
firstDigit = scanner.nextLine();
System.out.println("Please input Surname: ");
secDigit = scanner.nextLine();
CompanyEmployee.setPersonName(firstDigit);
CompanyEmployee.setPersonSurname(secDigit);
System.out.println(CompanyEmployee);
}
while (!firstDigit.equals("dasd"));
解决方案
请更新您的代码,如下所示
public class Main {
public static void main(String[] rez) {
Scanner scanner = new Scanner(System.in);
String firstDigit = "";
String secDigit = "";
List<Employee> listofemployee = new ArrayList<>();
do {
Employee companyEmployee = new Employee();
System.out.println("Please input Name: ");
firstDigit = scanner.nextLine();
System.out.println("Please input Surname: ");
secDigit = scanner.nextLine();
companyEmployee.setPersonName(firstDigit);
companyEmployee.setPersonSurname(secDigit);
System.out.println(companyEmployee);
listofemployee.add(companyEmployee);
}
while (!firstDigit.equals("dasd"));
推荐阅读
- python - 使用 pyad 创建用户且密码未过期
- c# - 分配证书时 C# 对象是只读的
- web-services - 使用 Mockito 模拟 SOAP Web 服务并使用 JMeter 测量其性能
- javascript - 构造正则表达式以仅允许一个“+”
- google-analytics - 动态注入谷歌分析
- c++ - gitlab-ci.yml cpp 覆盖率报告
- python-3.x - urllib 和“SSL:CERTIFICATE_VERIFY_FAILED”错误
- android - 从 API 调用中读取 int
- bash - Bash 脚本 - 在 emal 中显示十进制变量
- java - Sonar maven 插件在类路径中看不到父类