Skip to main content
Lesson 6 - Defining and Using Classes
ZIPPDF (letter)
Lesson MenuPreviousNext
  
Using Classes page 8 of 11

  1. Using the CheckingAccount class is best demonstrated by writing a program that solves a specific problem. We want to study the following scenario:

    A interest bearing checking account is created with a balance of $1,000. For two years in a row, add 2.5% interest. How much money is in the account after two years?
  2. Two classes are required: the CheckingAccount class that was developed in the preceding sections, and a second class called CheckingTester. The main method of the CheckingTester class constructs a CheckingAccount object, adds the interest twice, then prints out the balance.

    class CheckingTester
    {
      public static void main( String[] args )
      {
        CheckingAccount checking =
            new CheckingAccount("A123", 1000);
    
        final double INTEREST_RATE = 2.5;
        double interest;
        
        interest = checking.getBalance() * INTEREST_RATE / 100;
        checking.deposit(interest);
    
        System.out.println("Balance after year 1 is $"
            + checking.getBalance());
    
        interest = account.getBalance() * INTEREST_RATE / 100;
        checking.deposit(interest);
       
        System.out.println("Balance after year 2 is $"
            + checking.getBalance());
      }
    }
  3. The classes can be distributed over multiple files or kept together in a single file. If kept together, the class with the main method must be declared as public. The public attribute cannot be specified for any other class in the same file since a Java source file can contain only one public class.

  4. Care must be taken to ensure that the name of the file matches the name of the public class. For example, a single file containing both the CheckingAccount class and the CheckingTester class must be contained in a file called CheckingTester.java, not CheckingAccount.java.


Lesson MenuPreviousNext
Contact
 ©ICT 2003, All Rights Reserved.