Software Sue

Link to Simply Sue
Link to Sustainability Sue
location: software/java/class Skip navigation : Home  

Specifying a Java Class


Java is an object-oriented language. The objects you use will reflect the problem to be solved in real life, for example BankAccount objects or Recipe objects. Java still has the basic numbers and characters data types too but in Java nearly everything is an object. Collections of objects with common properties are called classes. MySavingsBankAccount could be an object of the class BankAccount. Java code is used to express the defined properties of the class. You can define the class with as much or as little detail as you need - a bank would probably have a much more complex definition of BankAccount than an individual, for example.

Using object-oriented design makes development and later enhancements easier. The standard classes that come with Java are also useful. Having an object include both its data definitions and methods together, makes programming less error-prone, and therefore more robust than the equivalent code of procedural programming languages. Maintenance is also easier. Although the design stage can take longer because of the necessity to design classes, the coding may take considerably less time.

(For more details about the topic of Object Oriented Programming in general, see my web pages on the subject.)

Every object you use in a Java program will belong to a class you have defined, and is called an instance of that class. MySavingsBankAccount would be an instance of the class BankAccount, for example.

Specify just the objects and parameters that you need in a class definition, depending one what's needed for the parameters you want to solve. For example, to keep track of your BankAccount, you might want only the balance, transaction date, type of transaction (e.g. standing order), and the amount. Others might prefer a lot more detail. These parameters are called instance variables or attributes of a class. Instance variables can be simple data types, or can themselves be objects. The process of selecting only the attributes that you want is called data abstraction. Attributes can be fixed (e.g. account number) or can vary (e.g. balance).

A Java class takes the form:

class Classname {
  // definition of the class
}

The word class is a Java keyword, so you cannot use it for anything else. '//' means that what follows on the same line is a comment, not code.

A class differs from the complex data types of in some other programming languages in that it includes definitions of the operations that you can do on that class. Again, you specify only those operations that you want (assuming of course that they are practical). You may need a few not so obvious ones, such as one to convert input integers to floating point before performing arithmetic on it.

An operation is defined as a method, which is a self-contained block of program code. You can pass data items to methods, and methods can return a data item as a result. Data items can be character strings, class objects, floating point numbers or integers. You execute the method that defines the operation in order to perform the operation. For any given class, you can only perform the operations that you have defined for it.

Methods always have parentheses after their name both in their definition and when they are being used by a program, and they are also are referred to by their name followed by parentheses in text to distinguish them from other names (cleanShoes() for example).

The name of the file holding a class specification is always in the form classname.java (.java contains source code). To create the following example, save the code as Shoes.java using a text editor. Note that the whole specification (attributes + methods) is contained within the braces {}, and // means that the rest of the line is comment, not code.

Class Shoes
{
// Specify attributes of class - the instance variables 

// private is a keyword used to ensure ensures that only code within the 
// methods of the class can access or change the values of these directly.

private string style		// the style of shoes
private int size		// the size of the shoes
private bool shoesClean = false	// whether the shoes are clean or not - default is dirty

// Special method called a constructor, to create Shoes object

// Constructor to create a Shoes object

// The items between the parentheses (String styling, int shoeSize) 
// after the constructor name specify the data that the user passes
// to the method when it is executed.

public Shoes(String styling, int shoeSize)
  {
  size  = shoeSize;		// set the shoe size
  style = styling;		// set the shoe style
  }

// Other class methods

// method to clean the shoes
public void cleanShoes()
  {
  shoesClean = true;		// record the shoes as having been polished
  }

// method to record that the shoes need cleaning
public void dirtyShoes()
  {
  shoesClean = false;		// record the shoes as needing polishing
  }

// Method to get the shoe size

public int getShoesize()
  (
  return shoeSize;		// return the shoe size
  }
}

Java statements

The program statements for a class are written between the braces {}.

Each statement ends with a semicolon, and can spread over as many lines as necessary.

Spaces and tabs can generally be included between words for readability, but cannot be put in the middle of a name, for example.

Encapsulation (private and public keywords)

Encapsulation means hiding data and methods inside an object. You do this by defining them as private. By encapsulating instance variables you make sure that they are only accessible via the methods you have defined for the class. You can then use those methods to ensure that the variables only take on the values you want, for example.

Encapsulation lets you hide the implementation of a class, which means that you can change the inner working of the class without the programs that use it having to change.

If an instance variable is made private, only code within the methods of the class can access or change the its value directly.

If a class method is made private, others cannot gain access and change the internals of the class from outside. This way you can make sure they can only access the bits of a class that you want, and you can change the other parts without affecting them.

Classes and Data Types

Basic data types such as numeric values, single characters or logical values (true/false) are not classes, although Java does have classes that correspond to them. Programs tend to work on the more complicated types of objects (or data types) that you specify as classes. Java also supplies a library of standard classes that you can use. Other suppliers also offer classes.

Subclasses and Superclasses

In Java (as in some other programming languages), you can subdivide your classes into more specialised subsets, which are themselves classes. For instance, you could specify boots, sandals, sports shoes or dancing shoes as classes derived from Shoes if you felt it useful. They would inherit all the attributes and methods of Shoes plus have some of their own - for instance the Boots subclass could include height. Shoes could be referred to as a superclass of the class Boots.

Java Programs

Structure

A Java program consists of one or more classes, each class being held in a source file named myclass.java after the class defined within it. For instance, a program concerning pets might have the following files: MyProgram.java, cat.java, dog.java, bird.java, hamster.java. As well as the source files you have created for your program, you will need code from the Java standard class library.

Java Class Library

A Java library is a collection of related classes, some of which are essential for programs to work, and others that make it easier. Each file in the class library contains one class. Related classes are grouped into a package held in its own directory, and each class in a package can access the other classes in it. They cannot necessarily access classes in other packages. The package name is related to the directory path; for instance the classes of the package java.lang are held in the directory path java\lang (java/lang in Unix). All the paths are relative to a directory specified by the CLASSPATH environment variable, so you should ensure that this is defined correctly for your system.

How?

Some commonly-used standard Java classes:

Package NameDescription
java.appletSupport windowed applications in Java.
java.awtUsed for implementing applets (awt stands for Abstract Windowing Toolkit).
java.awt.eventUsed to handle events such as moving mouse or clicking, in a an application using windows.
java.ioFor handling input and output operations.
java.langFor supporting basic language features, for instance handling arrays and strings. This package is always automatically loaded with your program, so its classes are always directly available.
java.utilVarious utility classes, for instance for managing data.

To use classes from packages other than java.lang, use an import statement for each one that you need. You can then refer to such a class by its class name. Otherwise you would need to specify the full path to each class each time you referred to it

Java Applications

The first method in any Java application should be called main(), even in one-class one-method programs. For example, create the following code as a text file OurFirstProgram.java (change "My name is Sue! How do you do! " to whatever text you want):


public class MyFirstProgram
{
  public static void main(String[] args)
{
    System.out.println("My name is Sue! How do you do! ");
  }
}

The whole of the above is the definition of the class MyFirstProgram. The following is the definition of the method main():


public static void main(String[] args)
{
    System.out.println("My name is Sue! How do you do! ");
  }

The public keyword means that the method is globally accessible, the static keyword means that it can be accessed even when no objects of the class exist, and the void keyword means that it does not return a value. The only executable statement is

System.out.println("My name is Sue! How do you do! ");

System is a class from the java.lang package that supports simple keyboard input and character output to the display. Out is an object from that class that denotes the standard output stream - your display screen. It is referred to by system.out. Println is the method belonging to out that you are calling. It outputs the text that you have passed to it by putting it inside the parentheses ("My name is Sue! How do you do! ") to the display. Thus you can call a class method using the format classname.objectname.methodname. The statement ends with a semicolon. You can then compile and run the program as described in 'Running Java Applications'. It should display the text:

My name is Sue! How do you do!