Return to index

 

Classes and Objects

 

Topics Covered :

* Objects

* Classes

* Inheritance

* Instantiating new objects (constructor methods and the keyword 'new')

 

What is an Object ?

 

Objects have two characteristics:

  1. the state they are in (i.e., their properties or attributes)
  2. and the behaviors they can perform. 

Consider an iPod MP3 music player.  Its state may consist of things like:

  • Title of current track
  • Track number
  • Volume setting
  • Playing/Paused/Stopped

Likewise, its behaviors may include:

  • Select a track
  • Skip forward
  • Skip backward
  • Change volume
  • Play/Pause/Stop

Pictorially, this can be represented as follows:


MP3 Player

State

  On / Off
  Track Number
  Volume Level
    Playing / Paused/ Stopped
   

Behaviour

  Switch on / off
  Increase Volume
  Decrease Volume
  Increase Track Number
  Decrease Track Number
  Play
  Pause
  Stop

 

Notice that the behaviours we have identified all change the state of the iPod - increasing the volume changes the volume level, etc. Internally, the iPod may carry out a behaviour by carrying out a number of sub-tasks - just as the behaviour 'make a cup of tea' involves a number of steps, such as 'fill kettle' etc.

Software objects are similar to real world objects in that they also have state and behavior.  The state of an object is stored in fields and their behaviors are implemented with methods

Fields are 'variables' in which you can store changeable data (i.e., values).

Methods are named pieces of code that implement the behaviors that the object is capable of. They often call submethods to help carry out the behaviour. Submethods are just like ordinary methods, except that they are 'private' and only called internally. The methods that an object offers to the outside world are termed 'public'.

Your computer may have an in-built MP3 player application.  This application is a software object representing an MP3 player with variables and methods corresponding to the states and behaviors listed above.

Of course, software objects don't always have physical world counterparts.  It is common to model more abstract concepts using objects. 

While many simple programs just use a single object, usually many different objects are used together to accomplish a task.  Both the software MP3 player and the hardware version are composed of many parts, each of which is an object in its own right.

 

What is a Class ?

 

In the real world there may be many objects of the same basic kind.  For example, there are many iPod players just like yours, all made by the same manufacturer.  In object-oriented terminology, your personal CD player is an instance of the generic class of CD players of that type.

Each instance has its own state (e.g., each will have different tracks loaded) but they all work in the same way (have the same methods defining their behavior).

When a manufacturer builds a iPod player, it uses a blueprint to construct it.  All iPods of that same model can be built using the same blueprint.  Likewise, in object-oriented programming you need a blueprint for constructing object instances.  These software blueprints are called classes.

For example, when writing an MP3 player class, you would declare variables to hold the player's state (title of track, volume level, etc.).  You would also declare and write instructions for the methods that the player implements (play, skip, etc).

After writing the class definition, you can use it to create objects of that class by instantiating them.   When created, each object has memory allocated to it to hold its variables (i.e., its state).  The state of each object created is separate from that of any others. 

After an object is created, its methods can be called to have it do something.

A class can also define static variables.  Static variables are not duplicated in each instance.  They store properties that belongs to the class as a whole.  Each instance of the class will get the same value when accessing a static variable.  Collectively, instance variables and static variables are referred to as member variables because they are all members of the class.

Static methods are similar to instance methods except that the class, rather than an instance of that class, executes the method.  Because the class itself is executing the static method, it cannot use any instance variables, only static variables.

 

Inheritance

 

In the real world, everything can be placed in a tree-like classification hierarchy. For example:

Hence a Cat is a type of Mammal, which is a type of Animal, which is a type of Thing.

In object-oriented programming, all classes also fit into a tree-like hierarchy.  This is referred to as a class inheritance hierarchy because classes underneath inherit the variables and methods from the classes above them.

Classes above a given class are called superclasses of that class.  Classes below a class are called subclasses.  When you create a new class you can specify its superclass in order to position it in the class hierarchy. If no superclass is specified, by default the superclass is class Object, the root class at the top of the Java class hierarchy.

Inheritance is a key feature of object-oriented programming because a class does not have to re-implement behaviors or properties inherited from its superclasses. We say that the subclass extends its superclass.

However, sometimes a subclass will need to re-implement a behavior found in its superclass, in order to carry out the behaviour in a slightly different way.  In this case the subclass can override the method found in the superclass.  It does so by implementing a method with the same name and same parameters (values passed to a method) as the superclass's method, but with a different behavior.

 

Creating ('instantiating') new objects

 

You generally create new objects of a given class by calling a special method in that class called a constructor.  (Occasionally, objects must, or can, be obtained by calling a 'factory' method that does the actual instantiation.) You do this using the new operator.  To call a constructor, you type new, followed by the class name, followed by the constructor's arguments, if any, in parentheses.

For example, to create a new Color instance using the constructor that takes three parameters specifying the red, green and blue components you would type:

new Color(0, 255, 0)

You can store this new object in a variable of class type Color:

Color col=new Color(0, 255, 0);

The constructor method itself is declared in the Color class file as:

public Color(int r, int g, int b) {

        ...

}

Constructor methods are declared a bit differently from other methods.  The method name must be the same as the class name, and you don't declare a return type for the method (because it always returns an instance of the class). 

 

The Structure of a Class

 

At a minimum, a class declaration must contain the keyword class followed by a class name.  Class names must be legal Java identifiers.  This means they should not be a Java keyword and must start with a letter and contain only letters, numbers, or the underscore character "_".  There is an additional convention in Java that class names should always start with an uppercase character.

<package statement, if used>

<import statements, if any>

<public> class ClassName <extends SuperClass> {

// Methods and variables go here in the class body

}

 

Comments

Note that any text after '//' to the end of line is a comment and ignored by the compiler. TJI shows comments in dark red if syntax formatting is enabled. Other comment forms are:

/*

comment

*/

and

/**

comment

*/

 

Import statements

Import statements specify which other classes or packages (code libraries) your class is going to use.  Import statements tell the compiler where to look for the class definitions that we will be using.

The import statements must be placed before the class definition, but after the package statement, if used.  They begin with the reserved word
import followed by either a specific class name or a package name with the wildcard asterisk (*).  For example, to import the class java.util.Random you would type:

import java.util.Random;

To import all the classes in the java.util package you would type:

import java.util.*;

 

We can use a package statement to organise our own classes into code libraries. In doing so, we must save our source files in a directory structure to match (we discuss this elsewhere, but note that TJI will take care of this when you create a new project).

 

Return to index