gpt4 book ai didi

java - 在同一个Java数组中调用扩展类函数

转载 作者:行者123 更新时间:2023-11-30 03:44:59 24 4
gpt4 key购买 nike

我有两个类 LoanBook 和 STLoanBook,STLoanBook 是 LoanBook 的扩展。它们都在同一个数组中:

private static final LoanBook[] books = new LoanBook[50];
books[0] = new STLoanBook("B129", "Soil Mechanics", "Engineering");
books[1] = new LoanBook("B238", "Basic Biology", "Science");
books[2] = new LoanBook("B563", "Company Law", "Business");
books[3] = new STLoanBook("B342", "Cost Accounting", "Business");
books[4] = new LoanBook("B754", "Robotics", "Engineering");

我试图调用仅在 STLoanBook 中的函数reserve(),当我通过for循环调用它时,它告诉我reserve()不存在,因为它正在检查LoanBook类。我该如何解决这个问题,因为我已经有循环检查类 SimpleName(),但它似乎仍然错误。救命!

最佳答案

您可以在 for 循环中使用 instanceof 运算符和casting,例如

    for (LoanBook book : books) {
if (book instanceof STLoanBook) {
((STLoanBook)book).reserve();
}
}

关于java - 在同一个Java数组中调用扩展类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25979298/

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