Return to index

 

TJI's Practical Introduction to Java

Part One

 

This practical introduction to Java comes in two parts. We will begin by looking at the 'bigger picture' - at the level of classes and object-oriented programming, particularly in the 'event-driven' arena of GUI based programs. The second part looks more closely at the details of the Java language at the lower level of variables, flow control etc. We could start the other way around, but in either case some things you will just need to accept initially and let a deeper understanding follow in time - just as when we learn our first natural language (and as is often now the preferred way to learn a second language, by exposure and on the basis of 'need to know' - that one learns something best when one needs to know it).

So, don't panic if it seems like tough going, just say 'ok' and keep going. After reaching a point where you can run an example, do that and then review the material again; and then again the following day. Over the weeks and months ahead, these strange looking conventions will slowly become second nature.

 

Classes and Objects

The world is made up of objects that interact with each other - and this is also true in the software world. Programs are tools that work on data. The data is input, processed, stored, communicated and output. We will look at GUI components in this guide because their visual nature allows us to keep the examples simple. The techniques for designing and using GUI objects can also be applied to other types of object.

Objects have 'state' and 'behaviour'. Consider a button - its state will include whether it is pressed or unpressed, enabled or disabled, its size etc. Its behaviour is that it can be pressed. These states and behaviours could apply either to a real-life button or a software button. In the Java world, we speak of 'fields' as the variables that hold an object's state, and 'methods' as defining its behaviour.

Objects come in many types and each type has sub-types. In Java, the type of an object is called its 'class'. Java comes with a ready-designed set of classes arranged into a tree structured hierarchy, just as we categorise all living things into such a hierarchical tree. You can not only use these classes to form your own programs, but also take an existing class and add some additional qualities to create a new class - in this way, you will almost never need to start from scratch.

Most software has a user interface because most software involves user interaction. In the past, a 'command line' was the main way for a user to input data and instructions, but these days most user interfaces are 'graphical' - employing menus, buttons etc, and a mouse, so that the user interface is far more flexible and efficient.

Most of the time a program with a graphical user interface ('GUI') is waiting for you to do something. When you select a menu item or press a button the program springs to life for a while and then waits again. At the point of the button press, an 'event' occurs, generated by the button and this will be received by any object that asked to listen to the event. That object, possibly with the involvement of other objects, will carry out some task. The program will usually let you know when and that it has finished the task and either present some kind of result or otherwise inform you of success or failure.

To accomplish tasks, objects communicate with each other by sending messages. A message is one object calling a 'method' of another object. When we say 'an event is sent to a listening object', this is also the calling of a method in the listening object. A method call may be just a simple signal that something has happened or changed (a notification) but usually this invoves a bit more information about the nature of the change. Most messages involve a request and many also expect a response. That is, usually information is sent by the calling object, and often information is also sent back to the caller.

 

The Examples

We will create a set of example programs that although simple, will demonstrate all the main features of object-oriented design and programming.

Java is a language for defining classes, creating 'living' objects from those classes and specifying all the inner details of their state and behaviour. So that a computer, which lacks the ability to interpret your intentions, can understand your design, it must be expressed carefully, following the syntactical rules defined in the Java language. Although difficult, writing Java 'source code' is far easier than writing the equivalent in machine code!

All code (fields and methods) must be contained within a class.

A class is defined like this :

public class A {

// fields and methods go here, inside the curly braces

}

Anything written in source code following '//' till the end of the line is a 'comment' and ignored by the Java compiler. Multiple line comments are also possible and take the following format:

/*

This is a

multi-line comment

*/

Placing comments within your source code is essential for allowing the source code to be understood - even to the author!

We can define our first example in a class called Example1 like this :

public class Example1 {

}

A 'package' in Java is a way to group classes by functionality. It is one of the ways to keep source code well organised. The classes provided in the Java development kit are arranged into packages. It is wise to do the same with our own classes.

A source file defined as being in package a.b must be placed in a directory path that ends with /a/b (relative to the 'base directory'). In this way, the organisation that a package provides has a physical reality. The java compiler and interpreter can find classes by looking in the subdirectories specified by the package relative to a base directory. There can be more than one base directory for a program and these are specified in the 'classpath'.

We will create a package called 'projects.example1' to store our program's classes ('example1' is a subpackage of 'projects'). The 'package statement' must be the first (non-comment) line in a source file. Next is written a list of any other packages that will be used, using the keyword 'import'. We will use class JButton that is in package 'javax.swing'

So our basic class definition will be :

package projects.example1;

import javax.swing.JButton;

public class Example1 {

// fields and methods go here, inside the curly braces

}

The class JButton in the Java development kit suits our purpose perfectly. So we do not need to create our own button class, but simply use the existing one, by 'importing' the package it exists in and then creating an object of that type.

Next we need to add a 'constructor' - a special method that will be called when creating an object (also called 'instance') of the class - so that an instance can be created of our example class. In the constructor we can do any initialisation required. We will call the constructor of our JButton to get an actual button object; we also define a name ('identifier') for our button object. Later, when we want to run our example program, the constructor of our class will be called and in turn we call the constructor of the button.

So now our class looks like this :

package projects.example1;

import javax.swing.JButton;

public class Example1 extends JPanel {

JButton button;

public Example1() {

button=new JButton("Light");

this.add(button);

}

}

By defining button outside of the constructor (and, indeed, outside of any method) allows the identifier 'button' to be referenced throughtout the class - in all the methods of the class.

Indenting is not a required part of the Java syntax but it greatly helps us to see the structure of the code - so good layout is essential when writing software. That is why TJI provides assistance in this task and can automatically correctly indent source code.

We have introduced a number of very important features of Java in this last step.

Firstly, notice the import statement. javax.swing.JButton is the 'fully qualified' name of class JButton - the package is included in the name. Class JMenu (a menu class) is also in package javax.swing and so are many other classes. It is possible to declare that you will use a number of classes from the package by writing just one line that includes a '*' to indicate any/all of the classes in the package:

import javax.swing.*;

Secondly, notice that simple statements in Java are ended with a ';'

Inside the main body of the class (inside the outermost {}s) we define our button variable. We give the variable the name ('identifier') 'button' and declare that is it of class type 'JButton'.

Next comes the constructor. A constructor is a special method called by the Java interpreter when creating an object ('instance') of a class. A constructor has the same name as the class.

All methods have a 'body' which is everything inside the following curly braces. Our contructor contains one statement that creates ('instantiates') a new object of class type JButton and assigns it to the identifier 'button' that we previously declared to be of class type JButton.

The 'new' keyword tells the Java interpreter to create a new object of class type JButton by calling the constructor specified after the 'new' keyword. This will automatically reserve the computer memory required for the JButton object, and run the code within the constructor, among other things.

In Java, '=' is the assignment operator. It does not have the meaning of 'equals' in the mathematical sense. More accurately, it means process the right-hand side and store the result in the left-hand variable. Technically, in this case the memory location (starting address) of the new JButton object is stored in another memory location called 'button'. Because that identifier is of type JButton, the interpreter knows that the parts of the button object it might need to refer to (such as its methods) can be found at known offsets in that memory area. Technically, we can say that the memory location identified as 'button' points to the button object.

After the name of the constructor is a pair of plain braces with the word "Light" inside. The text (String) 'Light' will be displayed on the button and will also (by default) identify the event generated when the button is clicked by a mouse; that is, the String 'Light' will be set as the 'ActionCommand' property of the button. This is the way class JButton works.

Inside the plain braces () immediately following a method (or constructor) name is where we can pass variables (data) to a method. We must pass exactly the number and types of variable specified by that method, and in the same order. Variables passed in this way are called the 'parameters' of the method. However, sometimes there may be more than one method with the same name but different parameters - we will see an example of this later.

Methods may return something but constructors never do. If a normal (non-constructor) method does not return anything, it must be specified that it returns 'void', which means 'nothing'.

The public methods of a class (including parameters and returns) form the 'contract' that the class presents to the outside world (other classes).

Lastly, we add our button object to the user interface by adding it to our main class; our main class is based on JPanel (extends JPanel) and forms the central area of our program's user interface. JPanel is a standard Java class found in the Java development kit. A JPanel is basically a GUI container for GUI components. All containers use a layout manager to arrange the GUI components added to the container. We will use the default layout manager, which for the JPanel container is class FlowLayout, so we don't need to specify a layout manager in our code as FlowLayout is ok for our needs. FlowLayout arranges components one after the other, left to right, like words on a page.

The keyword 'this' is short for 'this class'. Because there is no ambiguity here, we could leave out 'this.' and simply write add(button);

Now we are ready to run the first example !

You will notice that the project contains the class Example1, but also 5 other classes. That is because we are making use of a framework program that can be created by TJI ready for building onto.

The framework classes provide a menubar, toolbar and statusbar - so we have a way to close the program and could add our own menus and toolbar buttons etc. But we are only interested in the central area of the GUI in these examples. When you run the example, in the central area you will see our button marked 'Light'. You can click it with the mouse. But nothing else happens - yet ...

In the next section we will add a second component to the GUI that responds to the button.

 

Download and run ...

You can download the source code for the example programs as a TJI project from the 'Resources' page of our website.

(c) Kinabaloo Software

Return to index