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'

ex.

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

mysavings.deposit(500);
system.out.println(mysavings.getBalance());

mySavings.withdraw(250);
system.out.println(mysavings.getBalance());

}
}

//this is in console

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

//output

- 500
- 250


Multiple Constructors

  • the constructor can be overloaded

Example
  • 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;
}


example

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.