• 1.0 Overview Objects & Classes


    Object Orientated (OO) Programming is a programming paradigm that is organised around “objects”.
    Classes” are templates for defining objects.

    The difference between classes and objects can be confusing, however, it is simple. A class is the code the programmer creates and an object is what is created when the computer executes the code for the class, i.e. an object is a particular instance of a class. As an analogy, think of the relationship between a blueprint and a car.

    A blueprint is a template that holds all the details for creating a car, much like a class is a template that holds all the details (code) for creating an object. However, until the car has actually been constructed it does not exist; all that exists is the blueprint for creating the car. This is the same relationship between classes and objects, a class can be thought of as a template that holds all the information for an object, but until the code has been run (instantiated) the object does not exist. The object only comes into existence when the program runs the class and creates an object.
  • 1.1 Objects


    Objects can be thought of as something of interest to a system/application. This allows developers to programmatically solve problems using a coding method focused on objects and their relationships. Objects in many cases represent “things” which exist in the real world. For example, a program that allows customers to buy books online will use objects representing customers, books and orders. A word processor program will deal with objects representing words and paragraphs. A computer game may deal with objects representing characters and scenes.

    Consequently, objects are characterised by states and behaviours. States are attributes (data) we know about the object, behaviours are procedures (methods) which can be performed by the object. For example:

    A door is an object.
    “Open” and “closed” are states.
    “Open door” and “close door” are behaviours.

    Objects can have a number of different types of relationship (association) with other objects. An OO application involves objects invoking methods of other objects to query/modify attributes.
  • 1.2 Object Oriented Concepts


    As previously discussed OO programming is class-based, i.e. fundamentally objects are created through programming and instantiating classes, consequently, classes define data fields & methods. An object of a class has its own values for fields and its own copy of methods. This allows multiple instances of a class to be created, i.e. multiple objects of the same class can exist simultaneously.

    OO languages incorporate concepts from other paradigms, such as the sequence structure, selection, iteration and modularisation. Objects (classes) can be tested in isolation and reused in different applications

    OO programming concepts:

    Data Encapsulation

    Data encapsulation is a mechanism used to hide an object’s state from “rest of world” through providing access to attribute values only through object methods.

    Abstraction

    Abstraction is a method for arranging and reducing complexity in a program by hiding, or abstracting away, complex features.

    Inheritance

    Inheritance is when an object, or class, is based on another object. It allows reuse of code facilitated by creating specialised subclasses which add fields and/or methods and inherit features of their superclass, leading to class hierarchies and libraries.

    Polymorphism

    Polymorphism is the ability to reuse method names by changing method signature (return type, number & type of arguments) or specialised code through overriding and overloading.

    Pluggability

    Pluggability is the concept of replacing one object with another without changing the other objects in the system

    Modularity

    Modularity is the concept of creating systems as interconnected independent objects for the purposes of pluggability and ease of debugging. Minimising the nature of the connections allows for maximum reuse.
  • 1.3 Classes


    A class is ‘template’ or blueprint for creating objects with well-defined states & behaviours. Java allows different types of classes including subclasses, abstract classes and local classes.

    A class defines object ‘types’ and object variables to be created through specifying fields (variables) and their types; which may include other objects (composition) and relationships (associations) with other objects.

    Classes can also specify methods that can trigger behaviours in objects. In the previous example where “open door” and “close door” are examples of behaviours in a “door” object. Methods would be written in the class on order for objects of the type door to execute the behaviours of opening and closing.

    Convention states that a class name begins with a capital letter. For example:

    class ClassName {..}
    

    Attributes (fields) are defined of a specific data type or structure which specifies permissible values and interactions (operations). For example:

    int integerField; int[] arrayField;
    

    Access modifiers define the scope of availability. They are typically private and can only be accessed/modified through object methods.

    Convention states they have a lower case initial letter, no spaces, and other words have no space and are capitalised:

    public void printDetails(..) {}
    

    Methods have a signature, which are its name and the number and types of parameters. Typically methods have a public access specifier if it is to be invoked by another object:

    doorObject.openDoorMethod();
    

    Private methods are for internal use by the object itself, this keyword allows object to refer to its own features. For example, “this” allows us to distinguish between the attribute x and the argument x of a method:

    this.x = x;
    

    Constructors are methods used in constructing objects; a constructor’s name is the same as the class name and has no return type. Classes can have multiple constructors, with different constructors initialising different combinations of states. Although Java creates a default constructor, it is better to define your own to initialise object fields:

    ClassName() {}, ClassName(int x) {}, ClassName(int x, String y) {}
    

    One constructor may invoke another using this:

    ClassName() 
    {
       this.(2, “suitableName”);
    }
    

    The new operator is applied to invoke a constructor and create an object instance:

    ClassName classObject = new ClassName();
    

    Accessors (getters) are methods used to access the object’s attributes – one method per accessible attribute value:

    public int getFirstField(){}
    

    Mutators (setters) are methods used to modify an object attribute:

    public void setFirstField(int firstField) {}
    

    Other methods may be used to ask the object to create new values/objects:

    toString()
    

    is often implemented to provide a String incorporating the current state of the object’s attributes.
  • 1.4 Example 1 (Menu Program)


    Screenshot taken from the menu at http://www.thedeli.be/media/The_Deli_Takeaway_Menu.pdf
    Screenshot taken from: http://www.thedeli.be

    A menu application could be developed through creating multiple objects of type item. Using the above image as a guide we can see that that the items fall into one of two categories: Burritos or Burgers. The items also have a name, a description, and a price. Consequently, we can write a class that to create an object with the previously highlighted states/attributes. This can be visualised using a class diagram:

    Class Diagram

    This allows us to create a menu by using a collection on MenuItems (see later). Now that we have the attributes for the items we must create the constructors and required behaviours (operators). When we create a new MenuItem we can use a constructor to set the MenuItem states, and we can add the operators that allow us to communicate with object (getters, setters, other methods). Again these can be visualised using our class diagram:

    class diagram extended

    Using the class diagram we can now develop the code for the class:

    Attributes:

    public class MenuItem { 
    // unique identifier
    private String name;
    // description of menu item
    private String description;
    // unit price of menu item
    private float price;
    // category e.g. burritos, burgers
    private String category; 
    

    Constructor (Note the use of this to refer to the object itself):

    public MenuItem(String name, String description, float price, String category) {
        this.name = name;
        this.description = description;
        this.price = price;
        this.category = category;
      }
    

    Behaviours:

    public String getName() 
    {
       // getName
       return this.name; 
    }  
    public void setName(String name) 
    {
       // setName
       this.name = name; 
    }
    
  • 1.5 Example 2 (Playlist Program)


    Playlist Screenshot

    PlaylistItem is the object of interest. It contains the following fields: name, time, artist, album etc. As In section 1.5 we can model the class using a class diagram:

    Class Diagram Extended

    As before where the Menu contained a collection on MenuItems, a Playlist will contain a collection of PlaylistItems. The Playlist is also an object and it is created in the exact same manner as we created “MenuItems” and “PlaylistItems”. It will utilise operations to play, add and remove items etc. We can therefore create a class diagram for the Playlist object and use it to visualise the relationship between the Playlist object and the PlaylistItem objects:

    Class Diagram Extended
  • 1.6 Variables & Data Types


    Variables are used to store information so it can be referenced by a program. They are used to hold data and need to be allocated to system memory. Variables are assigned a data type which is a classification for the type of data that will be stored. Data types determine:

    The amount of memory which will be reserved for, and or, used by the variable.
    Valid values for the variable.
    The operations which can use the variable value.

    The location of a variable defines the scope of a variable, i.e. the lifetime of variable and which statements can access it, for example, global variables are declared outside of a method and they can be accessed by any method, whereas local variables temporary values which are declared inside a method and can only be accessed by the method they are declared in.

    Examples of data types are

    Integers: int x;
    Characters: char c;
    Floating point numbers: float f;
    Boolean expression: boolean flag;

    Variables not only have different data types but there are also different types of variables. In this sense we can think imagine that there are different types of variables and each type of variable is assigned a data type. For example, there are:

    Instance variables

    Instance variables are variables for which each object (instance of a class) has its own instance of the variables. I.e. each object has its own copy of the variables which hold values specific to the object. Instance variables are used to define the attributes of an object.

    Local variables

    Local variables reside within methods. Local variables are initialised when a method is called and must be instantiated before use. Local variables can only be accessed inside the method in which they exist and cannot be accessed anywhere else in the class.

    Class variables

    Each object has its own values for instance variables, however sometimes you may want every object of a particular class to have access to the same variable, for example, in the previous example we may want all the PlaylistItems to have access to the total number of PlaylistItems. This can be achieved using a class variable. A class variables is a variable which available to all objects of a class. Class variables are declared using the static modifier and are associated with a class as opposed to an object. Consequently, each object shares the class variable which is in a single fixed memory location.

    Parameters & Arguments

    In programming the words parameters and arguments are often used interchangeably, however although the two terms are closely related there is a key difference. Parameters are used to pass data to methods. Parameters specify placeholders in a methods signature, i.e. between the two brackets, e.g.

    myMethod(String parameterOne, String parameterTwo)
    {
       String one = parameterOne; 
       String two = parameterTwo;
    }
    

    The actual data that is passed to the method is called an argument

    myMethod(“argumentOne”, String parameterTwo);
    

    Primitive Data Types

    The following tables lists primitive data types in Java:

    Type Size Range Default Value
    byte 8-bit -128 to 127 0
    short 16-bit -32,768 to 32,767 0
    int 32-bit -231 to 231 -1 0
    long 64-bit -263 to 263 -1 0L
    float 32-bit floating point (See Java Spec) 0.0f
    double 64-bit floating point (See Java Spec) 0.0d
    boolean 1-bit true and false false
    char 16-bit '\u0000'(or 0) to '\uffff'(or 65,535) '\u0000'

    Strings are often also treated as a primitive data type, however strings are objects; String class (java.lang.String). Strings values are enclosed in double quotes, whereas, single characters use single quotes.
  • 1.7 Methods and Data


    A method is a collection of statements that are grouped together in order to carry out an operation. Methods generally have five main components:

    1) A modifier (e.g. public, private) which changes how the method operates.
    2) Return type which specifies the type of data which the method will produce: Int, String, void.
    3) A name.
    4) A list of parameter which allow data to be passed to the method.
    5) A body which is comprised of statements which define what the method does.

    Garbage Collection

    Garbage collection is the process of identifying the objects in memory that as not in use and deleting them to free up the memory. When an object is created (instance of a class) memory for each of its instance variables is allocated and references are returned to the object. When no more references to the object exist in the application execution then a garbage collector reclaims the memory for future reallocation to new objects; the object either moves out of scope or its value is set to null.

    Expressions, Statements and Blocks

    An expression combines variables, literals, operators and method invocations to produce a single value which can be assigned to a variable of an appropriate type or used in a relational operation when compared to another value:

    a * b * c 
    

    A statement is a complete unit of execution terminated by a ;

    d = a * b * c;
    

    A block is a group of statements enclosed by {} e.g. a method body, control flow path.

    {
       d = a * b * c;
       e = d * 2;
    } 
    

    Operators

    An operator is applied to one or two variables/literals to produce a single new value which is often assigned to a variable or used in a an expression. Operator precedence is determined by parentheses. Operators with a higher precedence will be executed first (e.g. multiplication over addition). If operators share precedence they will be executed from left to right. Brackets can be used to override precedence.

    Arithmetic operators:

    Operator Meaning Example
    + Addition x + y
    - Subtraction x - y
    * Multiplication x * y
    / Division x / y
    % Remainder x % y
    ++ Increment x++ or ++x
    -- Decrement x-- or --x

    Values are dependent on type of operands. Can mix numbers but not numbers & non-numbers

    Relational operators:

    Operator Meaning Example
    == Equals x == y
    != Not equals x != y
    < Less than x < y
    <= Less than or equal x <= y
    > Greater thank x > y
    >= Greater than or equal x >= y

    Used for comparison and produce a boolean value. Can be used on numbers, single characters.

    Logical Operators

    Operator Meaning Example
    && And x && y
    || Or x || y
    ! Not !x

    Combine relational expressions. Operand(s) should evaluate to a boolean value. Instance of operator indicates whether a object is of a particular class

    Assignment

    Assignment is the process of using the assignment operator (=) to assign a value to a variable. The values can be a literal value, a value of another variable, or the result of an operation (e.g a method). When assigning a value, the right hand side (RHS) value must be of an appropriate type for left hand side (LHS) variable:

    int x = 5; x = x + 1; 
    

    A statement like int x = “string” would fail because the RHS is a string and the LHS an integer variable. The + operator can add numbers and also concatenate strings:

    String name = “FirstName “ + “Surname”; 
    

    Control Flow

    Control flow is the order in which the code is executed when running a program. Java executes statements in a sequence starting from a main method. A method call jumps the execution to the start of the method body and returns to the statement after the calling statement once the method finishes executing.

    To provide alternate paths through an application Java provides selection control structures. Control structures are processes which analyse variables and choose in what direction to proceed based on given parameters. Structure theorem dictates that programs can be written using three main structures (sequential, selective, and iterative).

    Sequential.

    Selective

    Binary selection is achieved using an if statement i.e. a choice between two alternatives. A condition is evaluated and statements grouped into a ‘true path’ and a ‘false path’

    if (condition)
    {
      // true-path
    }
    else
    {
      // false-path
    }
    

    Conditional Statement
    Multiple selection is achieved through using nested if statements

    if (condition)
    {
       // path-1
    }
    else
       if (condition-2)
         {
            // path-2
         }
         else
         {
            // path-3
         }
    

    Conditional Statement
    Where paths can be labelled, a variable is used to determine which path to execute and a switch statement used:

    switch (caseVariable)
    {
       case 1:
           // path-1
           break;
       case 2: 
           // path-2
           break;
       default: 
           // default-path
    }
    

    Conditional Statement

    Iterative

    Iteration involves repeating a statement/block of statements a number of times.

    Java provides three mechanisms:

    for – used for a fixed number of iterations

    while – used when the loop statements may not be executed

    do-while – used when the loop body is executed at least once

    In the first case the number of iterations must be determined before loop execution begins. Often a counter is used to count iterations from a starting point to an end point. In the other cases a condition is evaluated to indicate repetition or termination of the loop traditionally a for loop uses a variable with a starting value, an operation to modify the variable (in some form of sequence) and a terminating condition when the loop variable exceeds some end point

    for (loopVariable = startValue; loopVariableCondition; loopVariableOperation)
    {
       // statements to be repeated
    }
    

    A newer form is used to iterate over a collection

    i.e. examine every element of the collection in turn

    for (loopVariable : collectionName) { .. . }
    

    A pre-condition loop which will evaluate a condition before entering the block of statements

    while (condition)
    {
       // Statements to be repeated
    }
    

    ince the condition may fail on first evaluation the statement body may not be executed

    Conditional Statement

    A post-condition loop where the statement body is executed at least once

    do
    {
       // statements to be repeated
    } while (condition);
    

    All control structures may be nested inside each other provided they are ‘opened’ and ‘closed’ properly

    Conditional Statement

    Arrays.

    Array are data structures which group together data that has a collective meaning under single variable. Arrays are fixed size collections of the same type of variables which can be either primitive values or objects. Individual values are accessed through a subscript (index) value generally starting at 0 for the first element:

    int[] array_name
    

    The previous code declares a variable of integer array type.

    A new operator is used to allocate the necessary memory locations:

    array_name = new int[5]; 
    

    Initial values can be supplied at the time of creation:

    int[] array_name = {1, 2, 3, 4, 5} 
    

    The above array has 5 elements with the values 1-5. As previously mentioned 0 refers to the first element, i.e. array_name[0] refers to the first element and has value 1 while array_name[4] refers to the fifth element and has value 5.

    Array can also be multi-dimensional, i.e. can index more than one dimension of information. Multi-dimensional arrays have separate indexes for each dimension, e.g. a two dimensional array could be declared as:

    int[][] twoDArray = {{1, 2}, {3, 4}}; 
    

    Remembering that elements start as ZERO, twoDArray[1][0] refers to the second set of information twoDArray[1][0] and the first element in that set twoDArray[1][0]. Therefore twoDArray[1][0] has value 3 (the first element of the second set).

    The class java.util.arrays has a number of array manipulation methods including copying, sorting and searching information.