Next page | Contents page |

Classes

So we now know that a class is a recipe for making objects and it defines 3 kinds of things:

Usually the data should be private, only to be accessed by the methods (and initialised by constructors) of this class, not available for other classes to meddle with directly.

Some fields and methods may be static and that means they belong to the whole class rather than any object - more on this later.

Customer

So the following is how the Customer class from the previous page might be written, in file Customer.java.

	public class Customer
	{
		// Data fields (all private):
		private String firstName;
		private String lastName;
		private String accountNo;
		// There will also be fields to do with orders and payment but we don't know enough about those yet
		
		// Constructors (there could be several, with different parameters, overloaded):
		public Customer (String aFirstName, String aLastName, String anAccountNo)    // No return type
		{
			// Set the fields from the parameters:
			firstName = aFirstName;
			lastName = aLastName;
			accountNo = anAccountNo;
		} // Customer
		
		// Methods:
		public String getName ()
		{
			return firstName + " " + lastName;
		} // getName
		
		public Order [] getOrders ()
		{
			/* ... we cannot complete this yet because we know nothing about the class called Order ... */
			// TODO ...  (IDE's can give you a list of all your // TODO tasks automatically)
			return null; // This will be explained soon
		} // getOrders
		
		public boolean hasPaid ()
		{
			/* ... similarly we have not yet said how to work this out ... */
			// TODO ...
			return false;
		} // hasPaid
		
		// And also, because the data are private, some accessor methods:
		public String getFirstName () { return firstName; }
		public String getLastName () { return lastName; }
		public String getAccountNo () { return accountNo; }
		// Notice how the names of these methods are related to the field names: this is a widely used convention
	} // Customer

Once we have constructed an object we can refer to its public fields and methods by using the dot notation:

	String name1 = customer1.getName ();

But any attempt to access a private field directly will be rejected by the compiler:

	String accountNo1 = customer1.accountNo; // NOT ALLOWED because the field is private
Next page | Contents page |