RSS

INM350 Programming with Java Session 1

08 Feb

Session 1 – Introducing Java Programming and Object-Oriented Modelling

1.1 Introduction

Welcome to your first ‘session’ in Programming with Java, which I hope you find interesting and useful. Before starting this session, you should have read the ‘Module Information’ section on Moodle, which outlines the aims, objectives and structure of this entire module.

This and subsequent sessions contain mini tasks, questions and quizzes that will help you to explore some of the ideas in the module. These questions will be identified as shown below. More than many subjects, Java programming requires active learning in order to be able to use the language effectively. So please take the questions seriously, even if the temptation is to skip them and read the rest of the lecture materials instead.

Questions and mini-tasks look like this. You should normally complete them before continuing with the rest of the lecture.

Sometimes, to encourage you to pause and think about a question, you will need to click on a button such as the one below:

Click to reveal/hide answer.

At various points, you will also find asides and learningNotes, – pieces of background information or questions, that while not necessary to know in order to pass the module, may be interesting to you and provide a more fully rounded background to the subject. They should be particularly useful to those who may wish to continue Java programming beyond this module.

Asides will look like this. You can safely ignore them, but reading them may provide you with interesting topics of conversation with friends and family.

These lectures will make frequent use of Java examples to illustrate the ideas discussed. These will usually be shown as a darker panel containing program code along with line numbering to the left. To transfer any of the code to your own programs, simply select the code with the mouse and copy and paste into BlueJ (or any other Java code editor).

1
2
3
4
5
6
7
8
9
10
11
/********************************************************************
* Example Java Program code will be displayed like this.
* This code can be copied and pasted into your own programs.
* When you copy code, make sure you acknowledge the original source.
*
*********************************************************************/

public class Example
{
// Java code would be displayed here.
}

The code above was formatted for the web automatically by the program jFormat, a Java applet that I have written that will convert Java source code into coloured HTML instructions for display on web pages. You can use the applet yourself if you need to show Java code on the web or discussion posting on Moodle.

You may also find the Glossary of terms provided on Moodle useful for this module. Here you will find definitions and examples of over 100 terms and concepts used in this module. It is accessible from the ‘Resources’ section of this module in Moodle.

Finally, you should complete these sessions and associated practical exercises at a rate of one per week. This will involve a full morning’s lectures and practical every Monday from 9:00 to 12:00. You should read these materials in advance of the lecture, although there is no requirement to attempt the exercises until the lab session on a Monday morning. All students are required to use the discussion areas in this module and are encouraged to participate as fully as possible.

So let’s get going by considering the approach to programming that we will be following throughout this module.

1.2 Object-oriented modelling.

Java is an object-oriented programming language. The meaning of this statement will probably only become clear as you progress through this module and you develop your own programming ‘intuition’. Rather than give a technical definition of this rather overused term let’s make a few observations about object orientation in programming languages:

  • An object-oriented programming language allows object-oriented models of the world to be more easily translated into computer instructions.
  • Other examples of object-oriented languages include C++ (often used in game programming), Objective-C (as used for developing iPhone apps), PHP (partly) and numerous others.
  • It is possible to incorporate object-oriented ideas into virtually any programming language.

What these observations suggest is that the importance of object-oriented programming is not necessarily determined by the language, but the underlying modelling of the world. A language like Java simply makes the process of implementing an object-oriented model a little less awkward than with some other languages.

So what does object-oriented modelling involve? It should be regarded as a way of organising your thoughts when solving a problem. In particular, it involves breaking down a problem into smaller components each of which have certain predictable behaviours and are able to share information with each other. As will be the case throughout this module, it is probably best illustrated with an example:

Suppose that while sunbathing in your garden, you notice an entrance to an ants’ nest. You observe that the ants that leave this nest appear to be showing rather complex behaviour, spending some of their time exploring, taking food back to the nest along linear ‘highways’, interacting with each other and other insects in the garden. Being of an inquisitive mind you decide to model their behaviour in the hope of predicting how they might spread across your garden.

The object-oriented approach to this modelling problem suggests that you need to break down the problem into smaller components or classes of things that might be easier to model. A sensible unit to start with is the individual ant, and we might model its behaviour as follows:

Class: Ant
Behaviour: Choose a random direction and walk for 100 paces in that direction until either:

(i) food is found – in which case take food back to nest leaving a chemical trail
or
(ii) a chemical trail is found – in which case change direction and walk away from nest along trail.

Repeat behaviour until back in nest or ant has walked for 100000 paces without food.

This simple model is a rather poor predictor of the behaviour seen in the garden, largely because it only contains a single ant (the ant’s path is shown in grey and it’s chemical trail, once it has found the food and begins to return to the nest, in brown):

We can make a more sophisticated model of the nest by simply adding lots of ants to it. This gives us a more complex model that is a little closer to the real world in our garden. Note how there are relatively few ‘chemical highways’ since a roving ant is more likely to come across an existing one than get to the food without meeting a previous ant’s trail.

Class: AntNest
Behaviour: Populate a central spot with 1000 objects from the class Ant over a 1 hour period.

There are two sets of advantages to this type of modelling approach.

Simplicity. The complex behaviour of a colony of ants has been made more manageable by breaking it down into simpler classes. The classes themselves in this example (ants and a nest) are relatively intuitive in that they correspond to real entities. If we (quite rightly) felt that a real ant was more complex than the model we have used, we might add further behaviours to our class as an eating behaviour, a walking behaviour and chemical communication behaviour. One of the claimed advantages of object-oriented modelling is that it better represents the way in which we organise our own way of thinking.

Extendibility. Note how easy it was to go from our Ant model to the AntNest model, simply by adding lots of instances of the previously defined class. Suppose an entomologist friend of yours had spent the last 10 years developing a more sophisticated model of a single ant’s behaviour. It would be easy to improve your nest model simply by replacing the Ant class with the new class. In doing so, we might not worry about the complex details of the model as long as we could observe its eating, walking and chemical trail laying behaviour. As we shall see later on, this idea of hiding the details of objects (known as encapsulation) is an important and frequently used one. We might also extend our nest model by identifying different types of ant (e.g. soldiers, workers and queen). We could use our existing model of the ant as the basis for these new classes, but then adapt it for each of the specialised types. This process (known as inheritance) is again widely used in object oriented modelling.

We shall revisit these ideas in in a little while as well as later in the module, but for now you should begin to think about how any given problem can be broken down into self-contained classes, each of which addresses a simpler aspect of the problem by adopting certain well-defined behaviours.

1.3 Creating a working Java program.

Let’s move away from object-oriented modelling for a short while and consider how we can write a Java program (note the American spelling of ‘program’ when referring to computer instructions) to do something for us.

Getting a working application in Java requires three stages. Firstly, the Java code is typed in using an editor. Any text editor will do (e.g. NotePad, TextWrangler or Emacs), although we will be using an Integrated Development Environment (IDE) called BlueJ that contains its own editor and helps manage our collection of object-oriented classes. For more details on other IDEs, see learningNote 48.

Secondly, we need to compile the Java code we have written. This process converts the Java text into machine readable bytecode. This bytecode is the same regardless of the computer used to generate it, so it can be shared across platforms (for example Java bytecode written on an Apple Mac could be used on a Windows machine).

Finally, once we have some compiled bytecode, we can run the program by passing the bytecode to a Java interpreter. The good news is that any IDE such as BlueJ can do this for us with the click of a button.

All this will make more sense once we see some real Java programs:

Have a look at Hello1.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/******************************************************************
* Hello1 – Program to display a simple text message on the screen.
* @author   Jo Wood.
* @version  1.4, 21st September, 2010
*
******************************************************************/

public class Hello1
{

// All java applications have a main() method.
// This one displays a simple message.

public static void main(String[] args)
{
System.out.println(“Programming With Java”);
System.out.println(“=========== ==== ====”);
System.out.println(“”);
System.out.println(“Program One: Hello World.”);
}
}

Note the following from this code:

  • Comments Any code that is enclosed by the /* and */, or any code on a line after a // is ignored by the computer when translating into bytecode. These are shown in green above. Comments are very important to us as they help to explain how the program works. All programs should start with a commented header explaining what the program does, who wrote it and when.

    You may have noticed the ‘@‘ symbols near the beginning of lines 3 and 4. These are special symbols that we will return to in a later session and are used for generating program documentation. For the moment, just be prepared to recognise and use @author and @version in the headers of all Java programs. You should always include the author of some code in a header, along with a citation to any other authors who have contributed to the code.

  • Classes are the main building blocks in the Java language and correspond the idea of the object-oriented class discussed earlier. This one is called Hello1 and its description is enclosed between { and } (known as braces). Note that all lines inside this class are indented by at least 4 spaces.
  • main() is the starting point for Java programs known as applications. As with the class definition, the description of main()is enclosed between braces and indented by 4 spaces. main() is an example of a method – a block of code that performs some specific behaviour.
  • System.out.println() is the code that actually does something. It prints the message enclosed between "quotes" on the screen. Note that each of these lines ends in a semicolon.

We shall ignore the remaining parts of the program for the moment. The important point is that you begin to get a feel for what a Java program looks like.

Running the program produced by this code would print the following on the screen:

Programming With Java
=========== ==== ====

Program One: Hello World.

Next, have a look at a more complex example that creates a window with a message inside it displayed on screen:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import javax.swing.*;        // Needed for graphic components.
import java.awt.*;

/***************************************************************
* Hello2 – Program to create a graphics window and display a
*          simple text message on the screen.
* @author   Jo Wood.
* @version  1.4, 21st September, 2010
*
***************************************************************/

public class Hello2 extends JFrame
{
// All java applications have a main() method.
// This one creates a graphics window.

public static void main(String[] args)
{
new Hello2(“Programming With Java”);
}

// This method has the same name as the class (Hello2) and is
// called a constructor. In this case it sets the window title.

public Hello2(String windowTitle)
{
super(windowTitle);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

// Create a grid of 2 rows and 1 column.
Container content = getContentPane();
content.setLayout(new GridLayout(2,1));

// Add two items to the window.
content.add(new JLabel(“Program two:”));
content.add(new JLabel(“Hello again.”));

// Size window and make it visible.
pack();
setVisible(true);
}
}

Much of this program will probably look unfamiliar, but the important points to note are:

  • Comments are used again to explain what the program does and who wrote it.
  • Each time a class or a method is defined, its description is enclosed by braces and indented by 4 spaces.
  • As before there is a main() method, only this time we have defined a new one as well [Hello2() in line 25].

When this program is run, a window similar to the following should appear (its precise appearance will depend on the operating system you are running):

Hellow in a window

So now we have seen a bit of Java, let’s revisit some the object-oriented design that we need to understand in order to use Java effectively.

1.4 Class design.

We have already seen that it is possible to model an aspect of the world by breaking it down into a series of classes, each of which can have a certain behaviour. So how do we apply that process to writing Java programs?

All working Java programs consist of one or more class definitions in which we create, name and describe each class in terms of two fundamental characteristics – a class’s state and behaviour. The state of a class is a list of properties it has, while a class’s behaviour is a list of things it does (we will explore these two aspects in more detail below).

So let’s consider how we might go about creating some Java classes to model something.

Suppose we would like to write a Java program that models the use and maintenance of a local park. Our first task is to consider the entities that might make up our park model. Just as we might when designing a database schema, we should think of an entity as corresponding to a useful real-world object that has identifiable characteristics.

Before reading on, you might like to have a go at doing this yourself. Try jotting down on paper 4 or 5 classes, each of which represents a different aspect of the park model. Under each class, try to identify some of its properties in terms of things it has and things it does.

Don’t worry if this all feels a little abstract at this stage if this is your first attempt at designing an object-oriented model. You will certainly get better at it as we explore these ideas in the next few weeks.

Click to reveal/hide answer.

Our Java program that models parks would contain 6 classes, one for each of the orange boxes in the class diagram above. Each class would contain information about its state and behaviour. So for example, the Tree class might be defined as follows:

Class: Tree
State: Tree type
Tree height
Age
Location
Behaviour: Grows by 5% per year.
Sheds leaves every autumn.

A class representing any tree

Classes and Objects

We shall look at how we might code a class’s state and behaviour in the next section, but first we must make an important distinction between the idea of a class and an object.

You may have noticed that despite Java being an ‘object-oriented language’ we have been modelling entities as classes not objects. So what is the difference between the two, and when do we use objects?

When we design an object-oriented model, what we actually do initially is try to create generic classes of things rather than specific instances of things. So for example, in the example above we created a Tree class that could be used for representing any tree. We can distinguish that from an object that might represent a specific instance of a tree, such as the one below.

Object: tree1
State: Type: Oak tree
Height: 17.5m
Age: 55 years
Location: National Grid Coordinates (344500,478240)
Behaviour: Will grow 87cm this year.
Will shed its leaves in 5 months time.

An object representing a particular tree

For those who are familiar with relational database design, there is an analogy here with the creation of the tables used to represent information. Creating tables and identifying the fields (columns) within them is equivalent to creating a class in object-oriented modelling. Populating the records (rows) within a table is equivalent to creating objects out of the class, where one row is analogous to one object. Unlike relational tables, objects are not only capable of storing data, but are able to enact behaviours, in other words process and manipulate those data too.

Separating the generic (class) from the specific (object) is one of several characteristics of object-oriented modelling that makes it a very powerful approach. Once we have created generic classes of things, we can reuse them in a variety of ways. For example, if you consider the park in described above, you should see that we actually have 3 separate instances of a Path – one running around and between the various areas of the park, one running though the flower area and one in the grass area. While each of these paths is in a different place, they all share the general characteristics common to all paths.

So let us turn now from the theory of creating classes and objects to the practice of doing so in Java:

1.5 The state of a class.

Remember the state of a class is a description of the information it could contain (tree height, age, location etc. in the example above). In this section we will consider how we get Java to store such information using variables.

For those who have ever programmed in other languages, the concept of the variable is likely to be a familiar one. But as we shall see, in Java we can store a range of types of variables from simple numbers to complex objects. But to start, let us consider how we might store simple numbers in Java.

Simple Variables

A variable is just a portion of the computer’s memory set aside to store someting, such as a number or some text. In Java, variables are sometimes referred to as fields. All variables have names to identify them which can be anything we want within certain limits.

Have a look at the following as an example of how variables can be used in a Java program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/******************************************************************
* Pythag – Program to demonstrate Pythogoras’ theorem for right
*          angled triangles. It demonstrates the use of simple
*          variables (fields).
* @author  Jo Wood.
* @version 1.2, 26th January, 2007
*
******************************************************************/

public class Pythag
{
// All Java applications have a main() method.
// This one does a simple pythagoras calculation.
public static void main(String[] args)
{
// Declare fields and initialise values (input).
int firstNumber = 17;
int secondNumber = 6;
int answer;

// Do the calculation (process).
answer = (firstNumber*firstNumber) + (secondNumber*secondNumber);

// Display the results (output).
System.out.println(“The square of the hypotenuse is equal to the”);
System.out.println(“sum of the squares of the other two sides.”);
System.out.println(“For example…”);
System.out.println(answer + ” = ” + firstNumber + ” squared + “+
secondNumber + ” squared.”);
}
}

Compiling and running this program will produce the following output:

The square of the hypotenuse is equal to the
sum of the squares of the other two sides.
For example...
325 = 17 squared + 6 squared.

Let’s examine this program in more detail:

  • As with all Java programs, we have started by defining a class, which in this case is called Pythag. Everything inside this class definition is indented by at least 4 spaces. Again, as with all other Java applications we have seen, there is a main() method. This is the start point for our program.
  • Comments are used to make the program clearer to read. The header at the top explains what the program as a whole does, the other comments explain each element. The input, process and output elements are emphasised in this case.
  • The input element involves declaring and initialising three variables (see below). Each of these variables will store a single whole number (integer). The number 17 is placed in the variable called firstNumber, 6 is placed in the variable called secondNumber, while the variable called answer is left empty.
  • The process element involves a simple calculation. The number stored in the variable firstNumber is multiplied by itself (the * means multiply) and then added to the contents of secondNumber multiplied by itself. The result of this calculation is placed in the variable answer.
  • The output element displays the results of the calculation on the screen. It uses the line System.out.println() which we have seen before, but this time in a more sophisticated way. If we wish to print the contents of the variables we have defined, they must be included in the println() call outside of the quotation marks. If they are to be combined with other text, they are separated by the + symbol.

Naming Variables

When naming a variable you should use a name that explains what it will hold. Don’t make variable names too long or too short.

The following are all legal and sensible names for variables:

answer1
pi
roadWidth

The following are all illegal variable names:

1answer (must not start with a number)
twenty-two/seven (must not contain mathematical operators)
road width (must not contain spaces)

As a general rule, the following are legal but poor names for variables:

a (what does this represent?)
variable (again, what does this represent?)
the_number_of_people_who_are_included_in_the_survey (a little cumbersome!)
SUMMARY (by convention variables are named in lower case)

As you may have already found out, all Java programs (and program names) are case sensitive. That is, Java would treat answer and Answer as completely different names. Although this might seem unnecessarily pedantic, it is useful for distinguishing certain types of variables and classes in Java. Here are a few of the naming conventions (more will follow later on).

  • all variables and methods should be in lower case. Where a name consists of more than one word, the first letter of each subsequent word should be capitalised (sometimes known as intercapping). So for example:

    roadWidth
    distanceToCentre
    setXYPosition

  • all classes should be lower case with an initial capital letter (as Pythag above). Note also that the file in which the class is defined should also have the same name as the class (but with a .java at the end).

You may also wish to look at the guidelines recommended by Oracle (1999) and, if you have time on your hands, how not to name variables (Canadian Mind Products, 2008).

Types of Variables

All variables must be declared when Java programming, telling the computer what sort of numbers are likely to be stored inside them. Variable declaration is usually done at the beginning of a method (as in Pythag.java above).

There are two basic types of number variables, whole numbers and real numbers. Each of these has several types depending on how large (or small) the numbers likely to be stored in them. These different types are known as primitives as they form the basis of numerical storage in Java.

Name Bits Minimum number Maximum number Type of number
byte 8 -128 127 whole number
short 16 -32768 32767 whole number
int 32 -231 231-1 whole number
long 64 -263 263-1 whole number
float 32 very small very large real to ~7 d.p.
double 64 even smaller even larger real to ~15 d.p.

The commonest type of whole number variable is the int (integer) type, which is suitable for storing typical whole numbers. If for some reason you need a variable to hold a larger integer than 231, then the long type can be used. On very rare occasions when it is critical to save memory and know that only small whole numbers are to be stored, you can use the short or byte variable types.

The commonest type of real number variable (i.e. one that holds a number with a decimal point) is the float type. This can hold numbers with a precision of about 7 decimal places. If you know you will require greater precision than that, you can declare double (precision) variables.

A variable is declared as:
variable_type variable_name;

For example,
int score;
double average;

Additionally it is possible to initialise a variable at the same time as declaring it. That is, a value is placed in the variable. It is good programming practice to declare variables and where possible initialise them at the beginning of a method or class.

A variable is initialised (and in these examples, declared also) as:
variable_name = value;

For example,
int score=0;
double average=50.0;

Typecasting

Java is known as a strictly typed language. This means that it is reluctant to let you assign variables of one type to another. For example continuing the example above, if you tried the line

score = average;

Java would try to place the number stored in the variable average into the variable score. In doing so, the Java compiler (javac) would come up with the error

Possible loss of precision. 
found: double
required: int
    score = average;
            ^

Although this might seem inconvenient, it would generally be bad practice to try to assign a double precision number to an integer since all the numbers after the decimal point would be lost. However, if we tried the line

average = score;

the compiler would not give an error. There should be no loss of precision in converting an integer to a double precision as the new value for average would now be 0.000000000000000.

A slightly more subtle version of this problem can arise when we assign numbers to variables. This is because whenever we use a number in a program, the Java compiler implicitly assumes it is an integer if it has no decimal point, or a double precision number if it has one. Therefore, the following would produce an error:

float temperature = 25.3;

The error is produced because Java tries to assign 25.3, which it assumes to be a double precision number, to a floating point variable.

The way round this is to use what is called typecasting. This involves explicitly changing one type of number or variable into another. It should always be done with caution since it can involve a loss of precision. To typecast a variable simply place the new type of variable in brackets in front of the variable/number to be changed. For example:

score = (int)average;
float temperature = (float)25.3;

Because the typecasting of numbers is more common than variables, there is a shorthand way of changing way numbers are represented. To represent a number as a floating point number place an f immediately after it. For example:

float temperature = 25.3f;

To consolidate, take a look at the following program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/******************************************************************
* Acidity – Program to illustrate the input, process and output
*           elements of a program. It also shows how variables of
*           different types may be declared, initialised and used.
* @author   Jo Wood.
* @version  1.3, 21st September, 2010
*
******************************************************************/

public class Acidity
{
// All java applications have a main() method.
// This one does a simple mean and difference calculation.
public static void main(String[] args)
{
//  Declare and initialise variables (input).
int    easting = 329440;    // National Grid coordinates
int    northing= 441660;    // of sample point.
int    sampleNum = 12;      // Sample point number (-1=missing data).

double acidityNew = 6.53;   // Soil pH at sample.
double acidityOld = 6.27;   // Previous pH reading.
float  change;              // Change in pH value.
float  average;             // Average pH value.

// Do the calculation (process).
change = (float)(acidityNew – acidityOld);
average = (float)((acidityNew + acidityOld)/2.0);

// Display the results (output).
System.out.println(“\n\n”);
System.out.println(“Soil quality monitoring.”);
System.out.println(“==== ======= ===========”);
System.out.print  (“\tFor sample number ” + sampleNum + ” at (“);
System.out.println(easting + “,” + northing + “)”);
System.out.println(“\taverage pH value is ” + average);
System.out.println(“\tchange since last sample is ” + change);
}
}

You should note the following from this example:

  • the use of comments to separate input, process and output elements of the program.
  • the conversion of double to float variable types in the process part of the program (lines 27-28).
  • more sophisticated use of output formatting in lines 31-37 (see below for further details)

Displaying Variables on Screen

The Acidity program above produces output as follows:

Soil quality monitoring.
==== ======= ===========
    For sample 12 at (329440,441660)
    average pH value is 6.4
    change since last sample is 0.26

Text can be combined with the contents of variables simply by adding the variable to the list of things to be printed i.e. inside the brackets of println() but outside the quotes. If a \n is included within the quotes, a new line is started rather than the characters \ and n being displayed. This represents one of several special escape codes that may be used to control output. The other one seen in this program is the \t code which indents subsequent text by one tab stop (about 8 spaces).

‘Printf’ formatting

Text output can be more fully controlled with a special output formatting method. The method System.out.printf() allows ‘C’ style formatting to be applied to text and numbers. Unlike System.out.println(), literal text and the contents of variables are separated and matched using special formatting controls. For example:

double answer = 1.23456;
int questionNum = 10;
System.out.printf("The answer to question %d is %.3f%n", questionNum, answer);

Formatting instructions start with the ‘%‘ symbol and allow whole numbers (%d), decimal numbers (%f) and new lines (%n) to be displayed. All the formatting codes are contained within “quotes” followed by a comma separated list of the variables to display. Decimal numbers can be formatted to an arbitrary number of decimal places by inserting a . and number between the % and f. Thus output from the example above would be:

The answer to question 10 is 1.235

For a full list of formatting codes, see download.oracle.com/javase/6/docs/api/java/util/Formatter.html

1.6 The behaviour of a class.

So far, we have concentrated on how we might get a Java program to store items of data by using variables that hold numerical information. Such variables help to define the state of an object. We have also seen that classes and objects don’t just store information, but they can be given particular behaviours. In this section we will look at how we can begin to program object behaviour using the concept of the method.

Methods

As we have already seen, a method in the Java language is a section of a class that does something. A method is identified with a unique name (just as variables are) and is followed by brackets (). The method itself is enclosed in braces {}. So far, all our programs have had at least one method called main() which is always the first method called by a Java application.

When designing a class, a method should correspond to an identifiable aspect of the class’s behaviour. So for example, if we consider our Tree class that we identified earlier on in this session, we might add a method to represent its growing behaviour :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//  **************************************************************
/** Class for representing trees.
* @author   Jo Wood
* @version  1.0, 14th May, 2001
*/
//  **************************************************************

public class Tree
{
// ————– Class and object variables —————–

private float height;        // Stores height of the tree.

// ——————— Constructor ————————-

/** Creates a new tree and gives it an initial height.
*/
public Tree()
{
height = 1;        // Set initial height at 1m.
}

// ———————– Methods —————————

/** Allows the tree to grow by 5%.
*/
public void grow()
{
height = (float)(height + 0.05*height);
}
}

As it stands, this program will not do much since we do not have a main() method, and the class needs to be linked with the other classes that make up a park. However, it does illustrate two important ways in which we can use methods.

The class consists of two methods, each of which manipulate the variable height in a simple way. The first method, called Tree is a special type of method called a constructor. For the moment, we can regard a constructor as a method that shares the same name as the class itself (Tree) and is called automatically whenever a Tree class is used. In this example, the constructor simply initialises the variable height with a value of 1m.

The second method, called grow() will not be called automatically, and as we shall see in the next session, must be invoked explicitly somewhere else in our Java program. If it were to be invoked however, it would find the current value of height and then increase it by 5%.

Don’t worry about the words private, public and void. These will be explained in the next session. For the moment what you should understand is that we can add many methods to a class to allow it to perform different behaviours. In terms of Java syntax and layout, each will have a broadly similar form to the ones shown above.

1.7 Making code clear.

A good computer program (in any language) should achieve two things. Firstly it should provide the unambiguous instructions in order for the computer to run the program. Secondly, the program should communicate to us what it is trying to achieve. In order to fulfil the second of these objectives, all Java programs should be easy to read and well documented. From the outset of your programming in Java, you should get into the habit of good layout and documentation.

This final section summarises some of the conventions and good practice we have already identified that will help you achieve this.

  • Use sensible names
    All variables, classes and objects should be given sensible names that describe what each does. These names should be concise and unambiguous as possible. By convention, all variable, object and method names are given in lower-case with ‘intercapping’ where necessary. Class names can be intercapped but should also start with an initial upper-case latter.
  • Indent code
    Java programs tend to be made up of blocks of code that make up classes, methods, and as we shall see in a later session, loops and conditional statements. Each of these blocks is enclosed in braces {}. The braces that enclose a block of code should always be vertically aligned making it easier to identify visually, the start and end of a given block. All code within a set of braces should be indented by 4 spaces or a tab. For example:

    public class AnyClass
    {
        // Code here is indented.
        
        public void anyMethod()
        {
            // Code here is indented by a further 4 spaces.
        }
    }
    There is an alternative convention of indenting and positioning of braces that you may well see in other people’s code. This convention places the opening brace of a block of code at the end of the preceding line, so that the example above would look like this:

    public class AnyClass {
        // Code here is indented.
        
        public void anyMethod() {
            // Code here is indented by a further 4 spaces.
        }
    }

    This has the advantage of saving a small amount of space on the page, but makes it harder to spot the structure of a program from its visual appearance.

  • Document Code
    Comments are vital when producing good understandable program code. You should get into the habit of placing comments in your programs as you write them, not as an afterthought when the program is written. In doing so you will find program development much easier and will be less likely to make mistakes. Java uses three types of commenting:

    // Single line comments are used for short comments that might explain a small part of a program, or perhaps explain what a variable will store.

    /* Multi-line comments can be used when
    a slightly larger explanation is required.*/
    This might include things like how to use the program, its copyright or development history.

    /** Javadoc comments are special versions of
    the multi-line comment.*/
    They are identified by having at least two ** at the opening of the comment. They should be used when creating a class header and explaining what a method does. We shall see in a later session why these are very important in the documentation process.

    Commenting code should be seen as part of the programming process. Usually when writing a Java program, the first thing you will do is design the class structure (as in our Park example above). Once a class has been created, its methods and fields are then likely to be identified. You can do this by creating a ‘skeleton’ class containing just the name of the class, any likely fields and methods. Each of these should be commented before you get down to the work of actually adding any further Java code. In this way it becomes easier to maintain a link between the abstract class design and the practice of building up Java code.

1.8 Conclusions.

In this first session we have considered some of the ideas behind object-oriented modelling by making a distinction between generic classes (e.g. any tree) and specific instances of objects (e.g. that tree over there). We have seen how our object-oriented models are likely to be made up of several classes, each of which are related in some way. So far, we have related classes via composition where one class ‘contains’ one or more other classes. This allows us to build more sophisticated classes as a grouping other simpler ones (for example, the created a Park class by composing it of some grass, flowers, paths etc.).

We have begun to see how we can relate the abstract process of object-oriented modelling to the coding process when creating Java programs. We have seen how each class in our design can be created in Java, with its own state represented by variables and behaviour represented using methods. Don’t worry too much if you still feel there is a large gap between the concepts behind object-oriented modelling and the process of writing in Java. You will practice linking the two perspectives in the practical and in later sessions.

Finally we have seen how we can begin to manipulate the contents of primitive variables in Java and display the contents of those variables using simple screen output. In doing so, the importance of good layout and naming conventions has been asserted. See also learningNote49 for more details on this.


A note about reading materials. Each week I will identify ‘recommended reading’ which you are encouraged to look at in order to meet the outcomes of the session. In addition, I will identify any further ‘references’ that were cited in the lecture materials. You are not required to read these references, although if you are interested in a particular topic they may provide useful information.

References

Canadian MindProducts (2008) How To Write Unmaintainable Code: Naming mindprod.com/jgloss/unmainnaming.html [accessed 20th September, 2011] This is part of a large document on how not to write program code. Packed with programmer’s in-jokes and subtlties well beyond the scope of this module, its intention is nevertheless serious by discussing the issues that prevent program code from being clear and maintainable.

Oracle (2011) The Formatter Class download.oracle.com/javase/6/docs/api/java/util/Formatter.html [accessed 20th September, 2011] For a detailed list of formatting codes for System.out.printf.

Oracle (1999) Code Conventions for the Java Programming Language hwww.oracle.com/technetwork/java/codeconv-138413.html [accessed 20th September, 2011] Some layout and naming conventions from the Java developers. Despite their recommendations, not all of the conventions recommended here have been universally adopted. However, it is useful in identifying why program conventions are helpful.

Recommended Reading

You are advised to look at at least one of the following:

Barnes, D. and Koelling, M. (2006 or 2008) Objects First With Java; Chapter 1 – Objects and Classes; Chapter 2.1-2.3 Understanding class definitions. London: Prentice Hall

Wood, J. (2002) Java Programming for Spatial Sciences; Chapter 2: Introducing Classes and Objects. London: Taylor and Francis ISBN 0415260981

Recourse: INM350 Programming with Java (City University London)

 
Để lại bình luận

Posted by on 02/08/2012 in Java

 

Gửi phản hồi

Mời bạn điền thông tin vào ô dưới đây hoặc kích vào một biểu tượng để đăng nhập:

WordPress.com Logo

Bạn đang bình luận bằng tài khoản WordPress.com Log Out / Thay đổi )

Twitter picture

Bạn đang bình luận bằng tài khoản Twitter Log Out / Thay đổi )

Facebook photo

Bạn đang bình luận bằng tài khoản Facebook Log Out / Thay đổi )

Google+ photo

Bạn đang bình luận bằng tài khoản Google+ Log Out / Thay đổi )

Connecting to %s

 
%d bloggers like this: