mardi 3 janvier 2017

If a method is defined in a super class, how to change outcome depending on the object calling it

I have a class called BankAccount (which is defined abstract) which is my super class and two children classes called SavingsAccount and CheckingAccount.

They both use the withdraw method defined in BankAccount however CheckingAccount can be overdrawn where-as SavingsAccount cannot.

My question is that if in the BankAccount constructor we have included the following:

public BankAccount(double balanceIn, double withdrawIn)
    {
        balance = balanceIn;
        withdraw = withdrawIn;
    }  

Which can be called from SavingsAccount class by:

public SavingsAccount(double balanceIn, double withdrawIn)
    {
    // initialise instance variables
    super (balanceIn, withdrawIn);

    }

is there a way of changing how the method responds depending on whether the constructor is called from the CheckingAccount or the SavingsAccount class

e.g (this is just to articulate and not real code, however a method defined in the BankAccount class which essentially does this)

public void setWithdraw(double withdrawIn)
{
    withdraw = withdrawIn;


    if (withdrawIn is called from savingsAccount && balance < withdrawIn)
    {
        System.out.print("You have insufficient funds");
    }
    else 
    {
        balance = balance - withdrawIn;
        System.out.print("Funds Withdrawn"); 
    }
}

I'm asking this because after some research I found out you cannot override the parameters from the super class in the child classes so it left me wondering how this was done. The SavingsAccount class would have its own attributes etc, I have left those out for clarity reasons (in-case you're wondering).

I know it would be a lot simpler to just put a withdraw method in CheckingAccount and another in SavingsAccount but since they both withdraw funds I wanted to see if it was possible to have it in the super class.

Aucun commentaire:

Enregistrer un commentaire