Answer the question
In order to leave comments, you need to log in
What can be done to avoid violating the dependency inversion principle?
I have a java program here, the essence of which is to make a transaction between two bank accounts. Everything works, but the dependency inversion principle is violated. How to fix it?
class BankAccount
{
private String AccountNumber;
private double Balance;
public BankAccount(String AccountNumber, double Balance) {
this.AccountNumber = AccountNumber;
this.Balance = Balance;
}
public void AddFunds(double value)
{
Balance += value;
}
public void RemoveFunds(double value)
{
Balance -= value;
}
@Override
public String toString() {
return "BankAccount{ " + "AccountNumber=" + AccountNumber + ", Balance=" + Balance + " }";
}
}
class TransferManager
{
public TransferManager(BankAccount Source, BankAccount Destination, double Value) {
this.Source = Source;
this.Destination = Destination;
this.Value = Value;
}
private BankAccount Source;
private BankAccount Destination;
private double Value;
public void Transfer()
{
Source.RemoveFunds(Value);
Destination.AddFunds(Value);
}
}
public class Bank {
public static void main(String[] args){
BankAccount from = new BankAccount("4321", 1200);
BankAccount to = new BankAccount("1234", 200);
System.out.println(from);
System.out.println(to);
TransferManager mymgr = new TransferManager(from,to,300);
mymgr.Transfer();
System.out.println(from);
System.out.println(to);
}
}
Answer the question
In order to leave comments, you need to log in
More or less like this:
interface IBankAccount
{
public void AddFunds(double value);
public void RemoveFunds(double value);
}
...
class BankAccount implements IBankAccount
...
class TransferManager
{
public TransferManager(IBankAccount Source, IBankAccount Destination, double Value) {
...
You probably do not quite understand what the dependency inversion principle is .
You don't use interfaces anywhere, everything is hardwired for you, for example, TransferManager can work with only one single type of BankAccount objects ....
PS Read about the code convention, because it's not easy to read your code.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question