Wednesday, January 17, 2007

Lecture 3

Continuing Bank Account Example

  • include the BankAccount object in a real program in order to use it.
  • a valid java program must contain a class w/ the special method 'main'


Public class mybank {

public static void main (string args[]) {

BankAccount mysavings = new BankAccount();

// 'new' is a java keyword
//the brackets are parameters passed to the constructor - to be explained in later lecture on overloading




//this is in console

javac -cp .
//-cp allows compiler to search current directory for class files


- 500
- 250

Multiple Constructors

  • the constructor can be overloaded

  • it can be multiply defined w/ different parameter declarations
  • previously we had:

public BankAccount() {balance = 0}

we could also have

public BankAccount(double id) {
balance = id;


BankAccount ac1 = new BankAccount();
BankAccount ac2 = new BankAccount(100);

  • java keyword 'this'
  • is a place holder for current method

public void deposit (double amount);
//balance = balance + amount // this is the old syntax we used
this.balance = this.balance + amount // using 'this'

  • both of these are legal

public void transfer (double amount, BankAccount x)

this.balance = this.balance - amount;
x.balance = x.balance + amount;

public BankAccount () {balance = 0;}

public BankAccount (double id) {balance = id;}

public BankAccount(){this(0);}

this(0); MUST be on the first line of the constructor and also calls the constructor.

To Review:

designing and implementing a class

  1. Consider the requirements of the class (system methods)
  2. Specify the public interface
    1. method declaration.
    2. Constructor declaration.
  3. Determine the instance fields
  4. implement methods
  5. test the object

1 comment:

Anonymous said...

Thanx for posting these lecture notes.