sepbar-1.gif (3106 bytes)

Java 102 : Dealing with classes

Written by David Reilly
Revised May 12, 1999
sepbar-1.gif (3106 bytes)

Previous | Next

Objects and classes are a fundamental part of object-orientated programming, and therefore Java. A class contains both data (referred to as attributes), and executable code (referred to as methods). In the previous tutorial, we created a class that contained a single method ' main '. When the class was executed, the main method was called, and the application ran as a normal program. While it is possible to use only a single class in a Java project, this is not good practice for large applications. The power object-orientation lies in breaking tasks down into simpler components that perform logically related tasks. Even a moderately complex program should be composed of many classes, which interact with each other.

When designing software with Java, we must deal with a large variety of classes. Each class is a separate module, which can interact with other objects through method calls. For example, we might design a bank account class, which acts as a record for storing salary data. Yet we can also include functions that modify or manipulate the data, such as calculating interest or depositing funds.

This class could then be instantiated by another class, creating a new bank account object each time. Don't worry if this terminology seems confusing at first - it will take a little while to sink in. We are basically creating an bank account object (which contains attributes and methods) that is defined by our bank account class. Each person would need there own bank account object - but all bank accounts share the same template (our bank account class).

We can instantiate an object by using the new keyword, and passing initialisation parameters. These parameters are evaluated by a special function called the constructor. The constructor is responsible for setting up the initial state of an object. Instead of declaring an object, and calling a special setup routine, a constructor is called automatically when the new keyword is used. For example, to create a new account, we might specify the initial balance, and it's defined for us without having to modify the attribute directly.

Of course, the constructor method isn't the only method that can change the attributes of an object. We can define other methods and then call them from our code. For example, we might define a deposit method for a bank account object. To call the method of an object, the syntax is object name.method name(params).

A simple example of constructing an object, and calling a method is given below. A function ' create_account ' instantiates a new account, deposits some money, and returns the account.

  // Create_account creates an account, deposits money,
     and returns an account
  public account create_account(double balance)
  {
     account my_account;

     // Instantiate a new object
     my_account = new account(balance);

     // Call the deposit method of our object my_account
     my_account.deposit(25.00);

     return account;
  }

To do the same thing in C, we would create a new instance of this bank account structure, and then we'd have to call functions that take the structure as a pointer reference. If you've used pointers before, you might appreciate just how handy it would be to have functions built into a structure.

After seeing how to instantiate an object, it might be a good time to examine how a class is defined. Carrying on from the original theme of an account, we'll specify an account class. The account class will need a constructor, and several methods such as deposit and withdraw. You can either type out the java source file yourself, copy it to the clipboard from this document, or download it directly.

It's also important to provide a public method for obtaining the balance, as we must hide from view the balance attribute. One of the handy features of object-orientation is that we can make private and protect from view certain attributes. This offers good security, as to change the value of these protected attributes a public method must be called. Thus, in this example, we can change the balance on our terms (through a withdrawal or deposit), instead of allowing some external object to change it for us.


/*
 *
 * Account
 * Demonstration for Java 102 tutorial
 * David Reilly, February 25, 1997
 */
public class Account 
{
        protected double balance;

        // Constructor to initialize balance
        public Account( double amount )
	{
		balance = amount;
	}

        // Overloaded constructor for empty balance
        public Account()
	{
		balance = 0.0;
	}

        public void deposit( double amount )
	{
		balance += amount;
	}

        public double withdraw( double amount )
	{
                // See if amount can be withdrawn
		if (balance >= amount)
		{
			balance -= amount;
                        return amount;
		}
		else
                // Withdrawal not allowed
                        return 0.0;
	}

        public double getbalance()
	{
                return balance;
	}
}  

Listing 1.0 - Account.java


After reading through the code, you'll probably have noticed that there are two functions called Account. A function that shares the same name as a class is always the constructor, but how can there be two?

Function overloading allows us to have more than one method interface. We can have a method that takes a double as a parameter, or one that has no value at all. This is handy, because we could refer to the constructor in more than one way.

        my_account = new account(250.0);
        my_account = new account();

Function overloading need not just apply to constructor methods either. We could create a function that takes multiple parameters, yet has a default set of parameters if no values are passed. It's even possible to specify different return types! We'll cover this in a future tutorial, but for now, we'll go through demonstration code that uses the Account class we created earlier.

In the following code, we create a new account (this time specifying no parameters). After depositing some money into the account, we call the println method learned in our first tutorial, and give it a string concatenated with the return value of getbalance (in this case, a double). One of the great features of Java is that it offers implicit type conversion to strings, and thus we do not need to covert a double value into a string.

After printing the balance, we withdraw money from the account, and then reprint the balance. You'll notice that we again concatenate a string with the return result of getbalance, using the ' + ' operator.


/*
 *
 * AccountDemo
 * Demonstration of Account class
 *
 */

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

                // 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());
	}
}

Listing 1.1 - AccountDemo.java


After running the code, feel free to modify some of the parameter values, and call different methods of Account to gain some experience with method calls under Java. In the next tutorial, we'll put to use some of our knowledge of classes, and cover file processing using the Java IO classes.

Previous | Next

<-- Back to the Java Coffee Break