//constructors CheckingAccount( String accNumber, String holder, int start ) { accountNumber = accNumber ; accountHolder = holder ; balance = start ; }
Another way to do write the constructor is by using this
//constructors CheckingAccount( String accountNumber, String accountHolder, int balance ) { this.accountNumber = accountNumber ; this.accountHolder = accountHolder ; this.balance = balance ; }
We have enough code to put together a test program. The test program will not do much, but it will compile and run.
// file: CheckingAccount.java // public class CheckingAccount { // instance variables private String accountNumber; private String accountHolder; private int balance; //constructors CheckingAccount( String accNumber, String holder, int start ) { accountNumber = accNumber ; accountHolder = holder ; balance = start ; } // methods }
// file: CheckingAccountTester.java // public class CheckingAccountTester { public static void main( String[] args ) { CheckingAccount account1 = new CheckingAccount( "123", "Bob", 100 ); System.out.println( account1.toString() ); } }
This can be copied to files, compiled, and run in the usual way.
C:\chap49>javac CheckingAccountTester.java C:\chap49>java CheckingAccountTester CheckingAccount@15db9742
Recall (from the previous chapter) that all objects automatically have a toString()
method which they inherit from the class Object
.
This inherited method returns a String
consisting of the name of the class and the address in memory occupied by the current object.
If you prefer, you could put both classes in its one source file.
Remove public
from the first class
and then compile as above.
The results will be the same.
With an IDE, you can test the CheckingAccount
class
without a tester program.
(Review: ) Do you think that the following would work?
public class CheckingAccountTester { public static void main( String[] args ) { CheckingAccount account1 = new CheckingAccount( "123", "Bob", 100 ); account1.balance = 10000000; } }