I have a quick question. I know how to use the keyword this in Java with a constructor that has parameters/arguments. Can you use this with a default constructor that has no parameters/arguments?
Example with code Class BankAccount below.
We created a method within this class to withdraw as much as possible. Within the method, I created a new BankAccount object to test with the tests provided by the Professor. Instead of creating theaccount object, he wanted me to use this. Is this possible without a constructor that holds parameters/arguments?
public double getOrAsMuchAsPossible(double requestAmount) throws InvalidAmountException, InsufficientFundsException
{
//Declare and initialize the variable amount to be used with in the method
double amount = 0;
//Create a new BankAccount object account
BankAccount account = new BankAccount();
//Deposit money into the account
account.deposit(400);
//Try to get requestAmount
try
{
//Set the amount to the request amount and withdraw from account
amount = requestAmount;
account.withdraw(requestAmount);
}
//Catch the exception with the InsufficientFundsException
catch(InsufficientFundsException exception)
{
System.out.println("Withdrawing amount: " + amount + " that is larger than balance: " + balance + " is not allowed");
}
//If the account balance is less than the amount requested
if(account.balance<requestAmount)
{
//The amount will equal the account balance, withdraw the amount from the account
amount = account.getBalance();
account.withdraw(amount);
}
return amount;
}
this(meaning this current instance) in any instance methods...thisquite yet.super()implicitly or explicitly if I recall correctly.this", the prof means for you to have your method do stuff only on thisBankAccount(i.e., theBankAccountinstance on which thegetOrAsMuchAsPossiblemethod is being called), not on some other totally differentBankAccountthat you've created for some special purpose.