|
home—info—lects—labs—exams—hws
textbook—tutor/PIs—java.lang docs—java.util docs
Last time, we wrote a test-class for a BankAccount. (What state and behaviors did that class have, again? Oh, right: it kept track of only one piece of state — a balance — and it had three behaviors (getBalance, deposit, withdraw).
Today, we'll actually write class BankAccount (and then check that it passes the BankAccountTester tests we wrote last time!)
Our test class was full of method calls — “asking questions of an object”. Today we'll look at the flip-side, writing methods — “telling objects how to answer questions”.
We'll start by talking about the signature for a method; this will be the other thing you'll need to memorize:
method-signature ::= return-type name( parameter-type&name )
We already figured out, that when somebody calls getBalance, they provide no additional information, and they expect to get a number back. Inside class BankAccount, we'll write:
double getBalance() { ... } |
Our test-cases also made it clear that when somebody calls deposit, they must provide the amount they want to deposit, and they don't expect any answer back:
void deposit( double amt ) { ... } |
The problem with just writing, say,
public double getBalance() { ... } |
public double getBalance() { return -12.345; } |
What about void methods, that don't return a value at all? You can leave those empty:
public void deposit() { } // This compiles as-is. |
class BankAccount is a blueprint for creating individual BankAccount objects (or “instances”). Whenever some BankAccount gets asked (say) the getBalance question, that BankAccount will follow the instructions as given in that method.
We've mentioned that constructors are methods, but are a bit funny: instead of being called with
method-call ::= object.methodName(args…) |
constructor-call ::= new ClassName(args…) |
Well, on the flip side of the coin, the syntax for a constructor's signature is a bit different too: instead of
method-signature ::= return-type name( parameter-type&name )we have
constructor-signature ::= ClassName( parameter-type&name )We see that constructor-signatures have two differences from regular signatures:
Let's add to our BankAccountTester class
BankAccount c = new BankAccount( 7.0 ); |
Now, if you've been watching closely, you'll wonder “wait — we never had a first version, with a constructor which took no inputs, so how did b = new BankAccount(); ever compile in the first place?” This is Java trying to fool us learners by being inconsistent: Usually we have to write every method, but:
gotcha: If you write a class and don't declare any constructor at all, Java writes one for you: a constructor with no inputs which does nothing.class BankAccount (stubs)
home—info—lects—labs—exams—hws
textbook—tutor/PIs—java.lang docs—java.util docs
©2009, Ian Barland, Radford University Last modified 2009.Feb.11 (Wed) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |