Java Reference
In-Depth Information
However, there is one situation in which it is legitimate to invoke a method
without, seemingly, an implicit parameter. Consider the following modification to
the
BankAccount
class. Add a method to apply the monthly account fee:
public class BankAccount
{ . . .
public void monthly-Fee()
{
withdraw(10); // Withdraw $10 from this
account
}
}
That means to withdraw from the same bank account object that is carrying out the
monthly-Fee
operation. In other words, the implicit parameter of the
withdraw
method is the (invisible) implicit parameter of the
monthlyFee
method.
If you find it confusing to have an invisible parameter, you can always use the
this
parameter to make the method easier to read:
public class BankAccount
{ . . .
public void monthlyFee()
{
this
.withdraw(10); // Withdraw $10 from
this account
}
}
109
110
A
DVANCED
T
OPIC
3.1: Calling One Constructor from
Another
Consider the
BankAccount
class. It has two constructors: a constructor without
parameters to initialize the balance with zero, and another constructor to supply an
initial balance. Rather than explicitly setting the balance to zero, one constructor
can call another constructor of the same class instead. There is a shorthand
notation to achieve this result:
public class BankAccount
{