sepbar-1.gif (3106 bytes)

Java 104 : Extending classes

Written by David Reilly, March 21, 1997
sepbar-1.gif (3106 bytes)

Previous | Next

Until now in this tutorial, the usefulness of object orientation and designing classes may not have been readily apparent. Certainly, bringing a data structure and functions that operate upon it together has its usefulness, but this has only just begun to scratch the surface. The real power that comes from using classes is that of inheritance - extending the power of existing classes.

Inheritance will probably be a reasonably new term for you, at least when applied to object orientated programming. Using other languages, you may have constructed libraries of source code, and enhanced them by adding to the original source. Inheritance offers a radically different outlook on the re-use of code, as you shall see shortly.

In Java, when we wish to extend the usefulness of a class, we can create a new class that inherits the attributes and methods of another. We don't need a copy of the original source code (as is the case with many other languages) to extend the usefulness of a library. We simply need a compiled '.class' file, from which we can create a new enhancement.

Furthermore, instead of re-writing a class to provide (as an example) a new function, we can simply declare we wish to extend a class, and add a few lines of code to get an enhancement. It makes the process of re-using code much simpler, and code easier to read.

To illustrate this point, we're going to take some code from a previous tutorial, and add some extra functionality to it. Remember the bank account example from Java 102? We're going to create a new class, that calculates interest and deposits this into the account. We don't need to re-write the original Account class, nor do we need to modify existing methods such as deposit and withdraw.



/*
 *
 * InterestBearingAccount
 * Demonstration for Java 104 tutorial
 * David Reilly, February 25, 1997
 *
 */

import Account;

class InterestBearingAccount extends Account
{
        // Default interest rate of 7.95 percent (const)
        private static double default_interest = 7.95;

        // Current interest rate
        private double interest_rate;

        // Overloaded constructor accepting balance and an interest rate
        public InterestBearingAccount( double amount, double interest)
	{
		balance = amount;
		interest_rate = interest;
	}

        // Overloaded constructor accepting balance with a default interest rate
        public InterestBearingAccount( double amount )
	{
		balance = amount;
		interest_rate = default_interest;
	}

        // Overloaded constructor with empty balance and a default interest rate
        public InterestBearingAccount()
	{
		balance = 0.0;
		interest_rate = default_interest;
	}
	
        public void add_monthly_interest()
	{
                // Add interest to our account
		balance = balance + 		
                        (balance * interest_rate / 100) / 12;
	}

}

Listing 1.0 - InterestBearingAccount.java


When we extend an existing class, we 'inherit' all of the attributes, and methods, of the parent class. Our new class can deposit, and withdraw - even though we never explicitly defined new methods for those functions. This makes programming much easier, and simpler, as we don't re-invent the wheel each time we extend other classes.

In the example above, we add only a single new function 'add_monthly_interest()', and override the constructors of our parent class. Overriding will be a new term for you - basically it means we replace the code for a function from a parent class with a new set of code. We must override the constructor calls for our class, as the superclass ' Account ' doesn't know about our new interest_rate attribute.

Now that we've created this new subclass, we need to provide an example program to test and demonstrate the new interest calculation capabilities. For this purpose, I'm using the demonstration program from Java 102 , and have added an extra call to the ' add_monthly_interest() ' method.



/*
 *
 * AccountDemo
 * Demonstration of Account class & subclasses of Account
 *
 */
import InterestBearingAccount;

class AccountDemo 
{
        public static void main(String args[])
	{
                // Create an empty account
		InterestBearingAccount my_account = new InterestBearingAccount();

                // Deposit money
		my_account.deposit(250.00);

                // Print current balance
		System.out.println ("Current balance " +
			my_account.getbalance());

                // Withdraw money
		my_account.withdraw(80.00);

                // Print remaining balance
		System.out.println ("Remaining balance " +
			my_account.getbalance());

                // Allow a month to pass
		my_account.add_monthly_interest();
		System.out.println ("Adding interest to account");

                // Print remaining balance
		System.out.println ("Remaining balance " +
			my_account.getbalance());

	}
}

Listing 1.1 - AccountDemo.java


As you can see, the example varies little from its original form in Java 102, save that we call the interest calculation function. You may also have noticed that the example calls a constructor that doesn't explicitly specify an interest rate. In this case, our constructor uses the default interest rate of 7.95%. Run this, and you'll see that it does indeed calculate interest for the account!

For those who would prefer not to have to type (or copy from the clipboard) the code for this tutorial, I've put together the full source code for this tutorial together as a ZIP.

By now you have learnt some of the basics of Java, and should be able to extend and modify the examples from the tutorial series. As practice until the next installment of this tutorial series, you might wish to modify the example to calculate the compound interest over the course of a year.

(Hint - use a standard for loop, calling add_monthly_interest() repeatedly).

Previous | Next

<-- Back to the Java Coffee Break