Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

invoking interface method in abstract class method

The code is running but I would like to understand the topic better and I am not sure how to name the problem. How is it possible that in abstract class method I can invoke an interface method if the interface method is empty? Could anyone please tell me how this kind of operation is called in Java? In my uni classes I attend, the slide names the problem as "Programming through API" but I cannot find anything when I google it.

I have an interface class which has getBalance method:

public interface BankAccount {

int getBalance();
...
}

Then I am invoking the interface method in an abstract Class method:

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);
}
}
like image 958
Marcin Kulik Avatar asked Feb 01 '26 01:02

Marcin Kulik


1 Answers

In an abstract class some methods are left for concrete inheritors to implement.

Although the method is empty (abstract) now, when you create a non-abstract implementation you'll have to give a body to that method. that body is what will be called.

Here is an example:

abstract class Parent {
  abstract String someMethod();

  public String getValue() {
    return someMethod();//how could this work?! someMethod() has no body!
  }
}

class Child extends Parent {

  @Override
  String someMethod() { //this won't compile unless I implement someMethod()
    return "data";
  }
}

Although someMethod() is abstract in Parent, you can't actually create an instance of Parent (because it is abstract). You have to extend it, which requires you provide an implementation of someMethod().

like image 135
Andreas Avatar answered Feb 03 '26 17:02

Andreas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!