Student Number:

Andrew Jones




Further Programming

Module Tutor:



Delivering College:


Mid Cheshire College

Assessment Number and Title:   2 – Abstract Data Types




  • This assignment is worth 100% of the module overall and covers some or all of the outcomes 1, 2, 3, 4, 5. 
  • The assessment method for this module has been split into four to spread student workload.   (Assignment Part A - 9%, Assignment Part B - 26%, Assignment Part C - 10%, Assignment Part D - 55%), however, the method of assessment is a single assignment worth 100%.
  • Refer to Module Descriptor for further details


Due Date:


4.00pm (1600hrs) on Friday, 11th December 2009






Mark awarded (re MAB):


IV assessor:






You are to demonstrate your understanding of the following programming concepts. Emphasis will be made on your use of own or other coded examples to explain the topic.


You need to show your understanding of:




Task 1

Object Orientated Programming – polymorphism.


Illustrate your knowledge by including annotated code examples to demonstrate the topic.



Task 2

Abstract Data Types – Illustrate three Abstract Data Types (ADT’s) from the following list :- arrays, linked lists, queues, heaps, trees or how a binary tree is traversed


Marks for this task will be awarded for program examples with written text, and graphical representation to explain the data type.



Task 3

Programming – demonstrate your knowledge of Java using annotated code examples and screen prints with supporting text. You must include the following topics:


  • packages and class library use, class constructors,
  • main class,
  • GUI controls,
  • Event driven programming (including action listeners)
  • Exception handling (try – catch)



Your report should be of sufficient size to show your knowledge and understanding. If you use references or examples of code from books or internet sites they have to be properly attributed (for example using the Harvard reference system) and in the case of internet sites the full address should be shown.

Table of Contents

Object Orientated Programming. 3

Polymorphism.. 3

Abstract Data Types 4

Arrays 4

Queues 5

Stacks 7

Programming. 8

Packages and class library use, class constructors 8

Packages 8

Class libraries 8

Class constructors 9

Main class 9

GUI controls 10

Event driven programming (including action listeners) 10

Exception handling. 11

Bibliography and References 12

Bibliography. 12

References 12

Polymorphism.. 12

Queues 12

Stacks 12

Packages 13

Class libraries 13



Object Orientated Programming

Text Box: interface vehicle {
    String manufacturer();
    String description();
abstract class motorVehicle implements vehicle {
    private final String manufacturer;
    protected motorVehicle(String manufacturer) {
        this.manufacturer = manufacturer;
    public String manufacturer() {
        return manufacturer;
    class sportsCar extends motorVehicle {
        public sportsCar(String manufacturer) {
        public String description() {
            return "i'm a sports car and am very fast...";
    class hgv extends motorVehicle {
        public hgv(String manufacturer){
        public String description(){
            return "i'm a lorry...";
    class van extends motorVehicle {
        public van(String manufacturer) {
        public String description() {
            return "i'm typically white and driven badly...";

    public static void main(String[] args) {
        motorVehicle[] vehicles = {
            new sportsCar("Porsche"),
            new hgv("Mercedes Benz"),
            new van("Ford Transit"),
        for (motorVehicle a : vehicles) {
            System.out.println(a.manufacturer() + " " + a.description());

Polymorphism is one of the core principles in Object Orientated Programming; two others are Encapsulation and Inheritance.

“Poly- meaning many, from the Greek polus meaning much; and, morphism meaning forms, from the Greek morphe meaning form.” (Fowler & Fowler, 1942)

So as polymorphism applies to Java and Object Orientated Programming it means that an object can have many forms. For example if we have an interface called vehicle we can create an abstract class called motorVehicle which implements vehicle with a methods called manufacturer() and description() we can now create subclasses of and extend the object motorVehicle() with subclasses such as sportsCar(), hgv() and van(),all of which have a method called description() which is different for each implementation of the subclass.

This offers the opportunity to re-use method names in the subclasses of an object.

Polymorphism gives us the ability, with inheritance, to re-use the same method signatures in subclasses of an object. Subclasses of a class are able to define their own unique behaviours; and, yet share some of the same functionality of the parent class.

There are a number of ways to use polymorphism in Java, the two most common are:

  • Method overloading, this is where methods with the same name signature but either a different number of parameters or different types in the parameter list.
  • Method overriding, this is where methods that are redefined within an inherited or subclass. They have the same signature and the subclass definition is used.

Abstract Data Types


An array is an object that contains elements of the same data type; its size is fixed at the time of creation. The items within an array are called elements and are referenced using a numerical value, which starts at zero.

Figure 1

In java code to create the array in Figure 1 above the code is as follows:

          int[] myArray;              // declares an array of integers

          myArray = new int[10];      // allocates memory for 10 integers

          myArray [0] = 10; // adds the value 10 to first element of the array

          myArray [1] = 12; // adds the value 12 to second element of the array

and so on until the array is fully populated.

Figure 2

Figure 2 shows a two dimensional array, or as it is more accurately described an array of arrays, and in Java code is constructed as follows:

          String [][] myArray;              // declares an array of strings

          myArray = new String[10][2];      // allocates memory for 10 rows and 2 columns

          myArray [0][0] = “and”; // adds the value and to first element of the array

          myArray [0][1] = “as”; // adds the value as to first row second column element of the array

          myArray [1][0] = “this”; // adds the value this to second row, first column element of the array

          myArray [1][1] = “an”; // adds the value an to second row second column element of the array

and so on until the array is completely populated.


A queue, as the name suggests, is a buffer for storing data before that data is processed. Queues typically operate on a First In First Out (FIFO) model; although there are a number of other queue behaviours: Last In First Out (LIFO) and priority queues – where queue elements are ordered according to their values.

In a FIFO queue all the elements added to the queue are added at the end or tail of the queue.

Queue methods exist in two forms, one form throws an exception and the other returns a value when the operation fails.

Methods that throw an exception:

·         Add(element)

·         Remove()

·         Element()

Returns a value

·         Offer(element)

·         Poll()

·         Peek()

Each queue implementation must specify its’ ordering properties; whichever ordering priority, the head of the queue is removed by utilising the calls remove() or poll().

A coded example of a queue is as follows:

Queue myQueue = new Queue(); //create a new Queue called myQueue

            myQueue.add(“first item”); //add the text first item to the head of the queue

            myQueue.add(“second item”); //add the text second item to the queue

            myQueue.offer(“third item”); //using the method offer add the text third item to the queue

            myQueue.offer(“fourth item”); //using the method offer add the text fourth item to the queue

            System.out.println("element: " + queue.element()); //prints to the console the item at the head of the queue using the method element()

            System.out.println("peek: " + queue.peek()); // prints to the console the item at the head of the queue using the method peek()

            myQueue.remove(); //removes the head of the queue using the method remove()

            myQueue.poll(); //removes the head of the queue using the method poll()



A stack in Java is a Last In First Out data structure. It extends the class vector with a number of specific methods:

1.    Empty() returns true is the stack is empty

2.    Peek() which examines the top of the stack without removing it from the stack

3.    Pop() removes the top elements of the stack and returns its’ value

4.    Push(element) adds the element to the top of the stack

5.    Search(element) searches for the element and returns its’ position in the stack

A coded example of a stack:

   Stack myStack = new Stack(); //creates a new stack called myStack

        myStack.push("first element"); //adds the text first element to the stack

        myStack.push("second element"); //adds the text second element to the stack

        myStack.push("third element"); //adds the text second element to the stack

        if (myStack.empty() == true) { //an if statement to evaluate whether the stack is empty

            System.out.println("the stack is empty"); //a print out to console if the stack is empty

        } //closing bracket for the if statement

        System.out.println("Peek: " + myStack.peek()); //prints to console peek: plus the contents of the tail of the stack

        myStack.pop(); //removes the tail of the stack using the method pop()

        System.out.println("first element")); //prints to the console the position in the stack of the searched for string first element



Packages and class library use, class constructors

Figure 3


Packages are groups of related types that provide access protection and name space management. Packages are defined by using the key word package, which is usually the first word in the source file followed by the package to which it is associated.

Class libraries

Class libraries are common functions and reusable code that the programme uses, typically they are imported for use, as shown in the code below:

import*; //imports all of the java input output library

import java.util.*; //imports all of the java utilities library

import java.lang.*; //imports all of the java language library

Or they can be accessed directly, as shown below:

java.lang.Math.random(); //a fully qualified reference to the function random()

The class libraries are grouped together into packages of related functions.

Class constructors

A class constructor is used to create a class blueprint for use within the programme. A class constructor is very similar to a method constructor; it contains the name of the class but does not return a value. The following code illustrates a class constructor:

public class sort { //creates a public class called sort

} //closing bracket for the class constructor

Main class

All Java programmes must have a main method with the signature:

public static void main(String[] args) //a method called main which is public static and void

This main class method provides an entry point and primary control for the programme; this is illustrated in the following code, which runs the gui interface for the programme:

public class Main { //class constructor for the main class

    public static void main(String[] args) { //a method called main which is public static and void

           java.awt.EventQueue.invokeLater(new Runnable() { //java library awt event queue invoke later new runable

                        public void run() { //public method run

                                    new gui().setVisible(true); //create a new instance of gui and sets its visibility to true

                        } //closing bracket for the run method


    } //closing bracket for the class constructor

GUI controls

Figure 4

Graphical User Interface (GUI) controls are the elements used when creating an interface for use in the programme. As shown in figure 4 on the right hand side are the swing library options for these GUI controls they are considered as light weight and are platform independent.

Event driven programming (including action listeners)

Event driven programming is a programme driven by events or actions performed within the programme. The flow of the programme is held in a waiting state until an action or more specifically an event occurs before auctioning the next set of instructions.

    private void cmdSortArrayBMIActionPerformed(java.awt.event.ActionEvent evt) { //button listener for an action performed

        sort.stringBubbleSortAscending(1); //call the method stringBubbleSortAscending from the class sort and pass the integer value 1

        txtTextArea.setText("");//set the text of txtTextArea to nothing

        CreateTable.main(); //call the method main from the CreateTable class

        txtTextArea.setText("Membership No\tBMI Rating\n"); //set the text of txtTextArea to Membership No tab BMI Rating

        for (int i = 0; i < Array.getLength(); i++) { //for loop based on the size of the array

            txtTextArea.append( //append text to txtTextArea

                    Array.getStringValue(i, 0) + "\t\t" //get the string value of row i and column 0, tab tab

                    + Array.getStringValue(i, 1) + "\n"); //concatenate the string value of row i and column 1, new line

        } //closing bracket for the for loop

    } //closing bracket for the action listener


Exception handling

An exception is an interruption to the normal operation of a programme. When an exception occurs it dislocates the regular flow of instructions. In Java the exception handling system is called try/catch. Where the code to run is encapsulated within the try statement, i.e. try and run this code and the exceptions are handled by the catch statement.

The code below shows a try catch statement for handling a number format exception:

/**check to validate that height is entered as a numeric value

     * using a try catch statement. Set error flags and then if error set the focus

     * to the height text box


    try                                                         //try statement

    {                                                           //opening bracket for try statement

        height = Float.parseFloat(txtHEIGHT.getText());         //asign the variable height from the text box txtHeight value as a float

        errorHEIGHT = false;                                    //set the error flag errorHEIGHT to flase, there has been no error

    }                                                           //closing bracket for try statement

    catch (NumberFormatException n)                             //catch number format exception aplha characters entered instead of numeric value

    {                                                           //openning bracket of the catch statement

        JOptionPane.showMessageDialog(                          //show message dialog box

                this,                                           //using this, the dialog box

                "You must enter a valid number for height in cm", //set the message text of the dialog box

                "Invalid Input",                                //set the title of the dialog box

                JOptionPane.ERROR_MESSAGE);                     //invoke the dialog box

        txtHEIGHT.requestFocus(true);                           //set the focus to txtHEIGHT text box

        txtHEIGHT.setFocusable(true);                           //grant the focus to the txtHEIGHT text box

        txtHEIGHT.setText("");                                  //set the contents of the txtHEIGHT box to nothing

        errorHEIGHT = true;                                     //set the error flag errorHEIGHT to true, there has been an error

    }                                                           //closing bracket for the catch statement

Bibliography and References


Fowler, H., & Fowler, F. G. (1942). The Concise Oxford English Dictionary (fourth ed.). Oxford: Oxford University Press.







Class libraries