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

时间:2014-09-22 16:56:47

标签: java arrays methods

我有两个班级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(),但它似乎仍然是错误的。救命啊!

5 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

您可以通过在LoanBook中创建方法reserve()来修复此问题,并在STLoanBook中扩展此方法,如果它不需要执行此方法可以执行此操作:

void reverse() {
    return;
}

在LoanBook中。

答案 2 :(得分:0)

您需要instanceof和演员:

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

答案 3 :(得分:0)

使用instanceof运算符

示例代码:

    A[] books = new A[10];
    books[0] = new A();
    books[1] = new B();
    books[2] = new B();
    books[3] = new A();

    for (A a:books) {
        if (a instanceof B) {
            ((B) a).reserve();
        }
    }

答案 4 :(得分:0)

首先检查对象是否是STLoanBook的实例。 如果是,则将其强制转换为STLoanBook,然后调用它上面的保留函数()。

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

另一个解决方案是为LoanBook编写一个空的reserve()函数并避免使用instanceof,但它看起来不像你需要的那样。