How to use callback mechanism?
callback, java
Solution
Changing Pin and getting the balance low is the behavior of CreditCard, so CreditCard object is event producer not event listener so you won't want to make CreditCard a listener (CallBack).
Actually your CreditCard will be calling back methods of the listener you want to be informed when any event like pinChange or lowBalance occurs.
Your code should look like:
class CreditCard{
int pin, balance;
private Callback callback;
CreditCard(Callback callback){
this.callback=callback;
}
public void pinChange(int pin){
this.pin=pin;
//inform the listener as well
callback.pinChanged();
}
public void withdraw(int amount){
this.balance-=amount;
//inform the the listener
if(balance<1000)callback.lowBalance();
}
}
class MyListener implements Callback{
public void pinChanged(){
//do what is needed when somebody changes pin..
//i.e send sms to the customer
System.out.println("PIN changed..");
}
public void lowBalance(){
//inform the customer about lowbalance.
System.out.println("little money in card..");
}
main(String... args){
CreditCard cc=new CreditCard(new MyListener());
cc.changePin(3306);
}
}
Hope this'll clear...
Problem
I have to implement a credit card application in which i have to handle only one Credit card account. Operations like `credit()`, `debit()`, `pinChange()`. But the problem for me is I have to use "JAVA CALLBACK" mechanism to notify user in two cases: - on pin change - when balance goes below 5000. How do I use callbacks for these notifications? The use of CALLBACKS is more of focus here.. ``` public interface Callback { public void onPinChange(); public void onLowBalance(); } import java.util.Scanner; public class CreditCard implements Callback{ Callback callback; int pin; float balance; public CreditCard() { callback = this; this.pin = 1234; // default pin this.balance = 10000f; // opening balance } public void creditBalance(float amount) { this.balance = this.balance + amount; } public void debitBalance(float amount) { if (balance <= amount) { System.out.println("Not enough balance to debit"); } else { balance = balance - amount; } if (balance < 5000) { callback.onLowBalance(); } } public void changePin(int newPin) { System.out.println("Enter the current pin"); Scanner scanner = new Scanner(System.in); int existingPin = scanner.nextInt(); if (existingPin != pin) { System.out.println("Wrong pin!"); } else { pin = newPin; callback.onPinChange(); } scanner.close(); } @Override public void onPinChange() { System.out.println("Pin changed"); } @Override public void onLowBalance() { System.out.println("low balance"); } public static void main(String[] args) { CreditCard card = new CreditCard(); card.changePin(3333); card.debitBalance(5200); } } ```