代碼正在運行,但我想更好地理解該主題,但我不確定如何命名該問題。在抽象類方法中,如果接口方法是空的,我可以調用接口方法嗎?任何人都可以告訴我在Java中如何調用這種操作?在我參加的uni課程中,幻燈片將該問題命名爲「通過API編程」,但當我在Google上搜索時找不到任何內容。調用抽象類方法中的接口方法
我有具有爲getBalance方法的接口類:
public interface BankAccount {
int getBalance();
...
}
然後我調用接口方法在一個抽象類方法:
public abstract class AbstractBankAccount implements BankAccount {
private final bankAccountNo;
private int accountBalance;
abstractBankAccount(int bankAccountNo) {
this.bankAccountNo = bankAccountNo;
}
public void transferBalance(bankAccount account) {
// so here is what I am struggling to understand: account.getBalance() is called, but getBalance() method in interface is empty, how does it work then?
final int accountBal = account.getBalance();
if (accountBal < 0)
throw new IllegalArgumentException("not enough money on the account");
accountBalance += accountBal;
account.withdraw(accountBal);
}
}
謝謝,掃清事情了我。 Java中的這種操作稱爲「通過接口編程」? – FervidWhirl