gpt4 book ai didi

java - 如何从包含多种对象类型的数组列表实例化对象

转载 作者:行者123 更新时间:2023-12-01 18:36:30 24 4
gpt4 key购买 nike

我正在创建一个软件作为评分作业的一部分。程序中有一个父类User,以及三个子类EmployeeShopOwnerCustomer

public class UserList {

ArrayList<User>Users;

public UserList(){
Users=new ArrayList<>();
}

当程序启动时,对象被实例化并添加到 UserList 中,这是一个应该保存 User 对象(包括其子类)的 ArrayList:

public void loadFromFile() throws FileNotFoundException, IOException{


FileReader reader;
reader = new FileReader(filename);
BufferedReader bin = new BufferedReader(reader);
String record = new String();

while ((record = bin.readLine())!=null)
{
String Name = bin.readLine();
String Password = bin.readLine();
String Role = bin.readLine();

switch (Role){

case "Customer":
Customer customer = new Customer();
customer.edit(Name, Password, Role);
add(customer);
break;

case "Employee":
Employee employee = new Employee();
employee.edit(Name, Password, Role);
add(employee);
break;

case "ShopOwner":
ShopOwner shopOwner = new ShopOwner();
shopOwner.edit(Name, Password, Role);
add(shopOwner);
break;
}
}

bin.close();
bin =null;

}

添加方法如下:

public void add(User src) throws IOException{

Users.add (src);

}

此时,我希望 Users(User 类型的 ArrayList)可以包含所有三个子类的实例。

在我的主要方法中,我需要初始化一个对象来访问子类Customer的方法,这就是事情变得困难的地方,我实例化了以下客户对象:

aCustomer = new Customer();

然后我尝试使用 UserList 类中的方法为其赋值:

aCustomer = theUserList.logIn(name,password,role);

登录方法如下:

public User logIn(String strname, String strpassword, String strrole){   
User currentUser = null;
for( User aUser:this.Users)

if(strname.equalsIgnoreCase(aUser.getName())&&
strpassword.equalsIgnoreCase(aUser.getPassword())&&
strrole.equalsIgnoreCase(aUser.getRole())){

currentUser=aUser;
}
return currentUser;

}

我意识到它返回一个User对象,而请求是实例化一个Customer对象,但是我很困惑logIn方法正在扫描Users,根据 loadFromFile() 方法,它应该包含所有三种对象类型。

错误如下:

enter image description here

我需要在主方法中访问客户对象。不确定旅程的哪一部分出了问题,这就是为什么所有内容都被复制的原因,所以对这个冗长的问题表示歉意。非常感谢任何指出从包含多个对象类型的 ArrayList 访问客户对象所需的更改的帮助。

我是 Java 新手,所以很抱歉,如果这是一个新手问题,请指导我如何在需要时更改问题,而不是关闭它,因为这个项目非常重要,我真的需要帮助。

编辑*

已使用向下转型尝试解决此挑战,并且不兼容的类型错误已消失,但该对象仍然无法访问客户方法 getBasket()。

User aCustomer = new Customer();
aCustomer = theUserList.logIn(name,password,role);
aCustomer.getBasket();

最佳答案

将返回对象从登录函数转换为用户类型

switch (role)
{
case "Customer":
Customer acustomer = (Customer) userList.logIn("A","B","C");
//System.out.println(acustomer.Name);


}

关于java - 如何从包含多种对象类型的数组列表实例化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60029958/

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