xxxxxxxxxx
// Java Program to Illustrate Dependency Injection
// Dependent class ExpenseTracker
public class ExpenseTracker {
// Class data member
private ExpenseCalculator expenseCal;
// Constructor
// Dependencies are injected
// using Constructor Dependency Injection
public ExpenseTracker(
ExpenseCalculator expenseCalculator)
{
// This keyword refers to current instance itself
this.expenseCal = expenseCalculator;
}
// Method
public void add(Transaction transaction)
{
int expense
= expenseCal.getTransactionAmount(transaction);
add(expense);
}
// Dependencies are injected
// using Setter Dependency Injection
public void setExpenseCalculator(
ExpenseCalculator expenseCalculator)
{
this.expenseCal = expenseCalculator;
}
}