Finally: Implementing methods

  1. In the preceeding discussion, we have arrived at the following design for BankAccount


    public class BankAccount { private double balance = 0.0; public void deposit(double amount) { ... (coming soon) } public void withdraw(double amount) { ... (coming soon) } public double getBalance() { ... (coming soon) } }

  2. Introducing a special keyword: this

    this always refers to the object that is currently invoking the instance method


    Example:
        BankAccount harrysChecking = new BankAccount();
        BankAccount momsSaving = new BankAccount();
    
        harrysChecking.deposit(2000);  // within deposit(), this 
    				   // will refer to harrysChecking
    
        momsSaving.deposit(2000);      // within deposit(), this 
    				   // will refer to momsSaving
    

  3. Now we can write the methods of the BankAccount class:


    public class BankAccount { private double balance = 0.0; public void deposit(double amount) { this.balance = this.balance + amount; } public void withdraw(double amount) { if ( amount <= this.balance ) this.balance = this.balance - amount; else System.out.println("Insufficient funds to withdraw $" + amount); } public double getBalance() { return(this.balance); } }

  4. You can get the BankAccount class here: click here.

    A test program that show you how to use the BankAccount class is available also: click here.

     

  5. Short hand notation:

    Because methods defined inside a class references frequently to (instance) variables and (instance) methods inside the same class, you will have to write a lot of this in front of variables and methods...

    So to cut down on the typing exercise, if you use an unqualified variable or invoke an unqualified method, then Java will automatically prefix the name with this.


    this.balance = this.balance + amount; can be written as: balance = balance + amount;

  6. So here is your first object class:


    public class BankAccount { private double balance = 0.0; public void deposit(double amount) { balance = balance + amount; } public void withdraw(double amount) { if ( amount <= balance ) balance = balance - amount; else System.out.println("Insufficient funds to withdraw $" + amount); } public double getBalance() { return(balance); } }
    Question: wouldn't the compiler prefix the unqualified variable amount as "this.amount" ??