Você está na página 1de 67

Chapter 1.

Object Concepts & Java

Introduction to the Module

CMT4120 provides a general introduction to the development of computer software


using object-oriented techniques. In particular it teaches the use of the Java
programming language. This module is provided as part of the MSc programme for
three reasons. First, software development is an important component of business
information technology. Second, we contend that some knowledge of software
development is important for all computer professionals, event those that do not
become directly involved in programming. Third, the concepts and insights gained from
following this course will support the student's understanding of the other course
modules in the programme.

The fact is easily overlooked that commercial use of computers (in fact all use of
computers) is possible because of the efforts of software developers. Software
development is an important and rewarding part of the commercial IT field. While this
MSc programme does not aim to train computer programmers, experience has shown
that a significant number of our graduates do go on to become professional software
developers in the commercial sector. We feel that the broad understanding of business
IT they gain by following this programme makes them better able to understand and
adapt to the environment in which they work than graduates of other computing
disciplines.

Even those graduates who do not intend to become professional programmers often
find themselves working with and around programmers, often as project managers. Too
often in business we find that the management of complex software projects is under
the control of people with little understanding of the day-to-day work of the people they
manage. We contend that one should be at least an adequate programmer to be an
effective manager of programming projects. The manager should understand at the very
least that the production of good quality software is difficult, requiring skill, knowledge
and a good deal of hard work, and this is certainly something the student will learn from
CMT4120.

The IT industry changes very rapidly, and the computing professional must develop
strategies to cope with this pace of change. One such strategy is to become more
aware of the theoretical foundations of IT. It is difficult to develop this theoretical
understanding by being an end user of software. To encourage ease of use, modern
computer systems and software have been developed in such a way that the technical
details of the operations they are performing are concealed from the end user. Most
software users, even very competent ones, have only a superficial understanding of
what the computer is really doing. However, programming requires a deeper level of
understanding. Learning to write computer programs encourages the student to confront
theoretical and technical aspects of computing that are normally concealed. This
strengthens the student's understanding of the key concepts and principles that will be
required to adapt to a rapidly changing industry.

Introduction to Unit 1

The purpose of this unit is to introduce the fundamental concepts of object-oriented


software systems. In addition this unit helps you install and understand the computer
programming development environment that you will be using in all later units for this
module (the Java Development Kit (JDK1.3) and Kawa 4.01).

Because it is the first unit of the module you will encounter a wide range of new
concepts. Maybe, if you have programmed before, the concept names will not be new,
but what the terms mean in object technology could be quite different. Dealing with a lot
of new concepts before putting them into practice can be hard, so you may have to
revisit this module later in the course to review the ideas. Certainly you should discuss
them on-line and in tutorial sessions.

Many new concepts that are relevant to object technology but not vital to the course (at
least not yet) are covered in the extension section of this unit. If you have time, you
should work through the additional content and activities.

Module Objectives

At the end of this module you will have acquired practical and theoretical knowledge
and skills about modern software development. Neither a long nor a short course can
produce expert programmers. When studying new programming concepts and a new
language it is very important to make sure you understand the fundamentals. So, after
successfully completing this module you should be able to do the following:

 understand and explain the main ideas of object technology


 differentiate between the various activities involved in software development,
especially in object-oriented programming
 read and understand complex Java software
 design, code and evaluate Java applets and applications.

Unit Objectives

Having successfully completed this unit you should be able to:


 Describe computer systems in terms of object-oriented system concepts, such as
encapsulation, abstraction, inheritance, and polymorphism
 Explain the difference between system software and application software
 Understand and use arguments when sending messages to objects
 Install a sophisticated software development environment and get it running

Study Planning

You should expect to spend approximately 9 hours studying this unit. However, if you
have never programmed before you may find that learning about programming concepts
and to program with Java takes considerable time and you end up taking more than the
9 hours. Often students find that the more time they invest in studying the basic
principles, as discussed in this unit, the more efficient they become later. You may find it
convenient to break up your study as follows:

Preparation (Introduction and On-line Planning): ½ hour


Disk-based Content: 2¾ hours
Application: 3 hours
Set textbook Content: none
Reflection (On-line discussions, review questions): 1 hour
Tutorial Work: 1 hour
Related Coursework: ¼ hour
Extension Work: ½ hour

Coursework and Exams for Module

The grade for the module is based on coursework (30%) and the final exam (70%). See
the Programme Handbook supplied in your course pack for detailed regulations. See
the on-line module calendar for this and other dates and any changes.

There will be a 2-hour, unseen examination – containing five questions, of which you
will have to answer any three. All questions carry equal weighting. The examination
contributes 70% towards the module’s final grade. The exam will take place in one of
the final two weeks of the trimester, when, except for a tutorial, there are no planned
study activities. Make sure you check the online calendar .

Prerequisites for Module

You should be a competent and confident user of PCs and operating systems such as
Windows 95, 98, and NT4.You must be proficient at using a Web browser. If you need
more practice with Web browsing, you should obtain and study an introduction to using
the Web, such as Lehnert’s Internet 101: A Beginner’s Guide to the Internet and the
World Wide Web and contact your LSC for support.

Equipment/software required

 Sun Java 2 Platform (also known as Java Development Kit 1.3)


 TextPad 4.5
 Microsoft internet Explorer 4 or later

Note you should install of the JDK (Java Development Kit) software development
environment, the JavaDoc JDK documentation, and TextPad 4.5 while studying Unit 01

Module Reading material and resources

Java: how to program. H. M. Deitel and P.J. Deitel, 3rd edition, Prentice-
Hall, ISBN: 0-13-012507-5

Online Resources:

1. Java Documentation
2. Kawa4.01 help
3. Frequently-asked questions

The links to 1 and 2 will be available to you after you have installed the Java
Documentation and Kawa4.01 provided with the software CD

Unit Reading material and resources

1. Carefully follow the instructions for installing Kawa4.01, and jdk1.3, which appear
on Apply page #1.
2. Set up the Unit 1 example applications described on Apply page #2.
3. The Deitel & Deitel book is only required in this learning unit for extension work.
Context

Object Orientation, sometimes called object technology, is a set of still-evolving


theories, techniques and tools for developing complex software systems. It is based on
the idea that software systems are best thought of as set of interacting parts, objects,
that do the work of the system by sending messages to each other. (Although the
Internet is not an object-oriented system, it is quite useful to think of object-oriented
systems as working in a similar way.) Object technology has particular strengths
because it allows developers to move in a relatively smooth fashion from that part of the
world that the software has to simulate to the software itself. For example, in an object-
oriented implementation of a banking system (i.e. in the code) you should find customer
objects that directly and straightforwardly represent how actual bank customers behave.

Most software development technologies evolve after a language has emerged that
best represents the ideas. The programming languages Simula and Smalltalk were the
starting points for object technology. Then came C++ and Java. C++ has some support
for object concepts and became hugely popular because of its relationship with C. Java
has given a further boost to object technology because of the Web, not to mention its
superficial relationship with C++ and its inclusion of many ideas from Smalltalk.–

Java is a relatively new programming language developed by Sun Microsystems, Inc.


Java started out in 1991 as a project code-named Green and the language was at one
stage called Oak. Java is thought by many to have been a compromise between what
its two inventors, James Gosling and Bill Joy, wanted. An early motivation was to design
a language for embedded systems, however other desirable language features were
added and Java is the result.

There are many existing computer programming languages, however Java has certain
features that motivated its creation and widespread adoption by software developers
and universities. One of these features is the portability of Java software – the same
‘pure’ Java software can run on many different types of computer system with no
changes, including PC-compatibles, Macintosh, and computers running a variety of Unix
systems.

Another feature of Java is that it is possible to create Java software (called ‘applets’)
that can be included as part of a web page, and so run on any computer with no
software required except a Java-enabled web browser.

A strength of Java is that it implements most of the concepts of object-oriented systems.


As will become apparent as you progress through the module, object technology
encourages and facilitates both software reuse, and the development of programs that
can model and respond well to modern, event-driven multi-tasking, graphical user
interfaces-based software systems.

Before learning about Java in the following units of the module, it is important to
understand the fundamental concepts behind computers, software systems and object-
oriented systems. This unit has been written in a way that presents ideas about
systems, software systems and object concepts first in abstract terms, then in more
concrete terms.

There are a lot of new concepts introduced in this unit, some are core concepts, others
are important background concepts for anyone studying and working with computer
systems. Use the activities and unit test questions to help focus on understanding and
apply the important concepts. You will probably find your self revisiting this unit each
time you complete a later unit, as your personal model of computing and computer
systems developed through the learning of object-oriented technology with the Java
programming language.

Computers and Software systems

Computers

A computer is a general-purpose device that behaves according to the sets of


instructions and data it is provided with. Computers execute instructions to process
data. Each computer has at its core a central processing unit (CPU) – these days CPUs
are built as a single microprocessor chip. Examples of common microprocessors
include Pentium, PowerPC, StrongARM, SPARC and Athlon. Any given computer can
only execute instructions in the machine code language of its microprocessor. However,
it is possible to translate instructions from one computer language to another. The
details of how it is possible to translate and run programs written in Java on a variety of
different types of computer (with different microprocessors) is investigated in the next
unit.

A high level view of a computer is that is runs a software system that accepts input,
processes the input according to its instructions and produces output. The order in
which input arrives and output is produced may not be predictable. Complex systems,
like the Internet or like airline booking systems, are supposed never to stop once
started. The simplest systems we usually call programs. They tend to have a simple
structure of taking input, then processing it, then outputting something and then stoping.
A computer does not distinguish between the types of low-level instructions and data it
processes, but we humans need to. We need to use different strategies for working out
what might be involved in complex systems and programming them than we do for
simple programs.

Systems

All systems are composed of interconnected components. The boundaries of a system


may be physical, or, most often, conceptual – i.e. what comprises a system is defined
by the human observer. For example, if one talks about the system for a department of
some company, it might (or might not) include the clients, the technical staff, the
company-wide computer network. If one talks about a heating system, it might consist of
just the hot water tank and thermostat, or it may include the pipes around the house and
to the cold water storage tank, or it might also include the tap fittings and bath, sinks
etc. and so on. Of course, at the end of the day, a system analyst will make decisions
as to the boundaries of the system for a particular project.

Resulting from the idea of the boundaries of a system is the associated idea of the
external system that exists outside the boundaries. It is up to the system analyst to
identify the particular system appropriate for a project, and also the interactions that this
system has with the external system. For example, the boundaries for a sales
department system might be set in terms of the tasks performed by members of the
department, so members of the external system would include customers, suppliers,
other departments and so on. The members of the external system interact with the
system, so customers place orders to the department, supplied supply goods and
present invoices for payment, and the sales department sends information and goods to
other departments to arrange payments and delivery.

The figure below illustrates how a software system is made up of communicating


software component objects. Each oval represents a software component object, and
the lines between the objects illustrate how some objects that make up the system
communicate to each other. As can be seen, in one case a component object is itself a
system, i.e. a component object can itself be a sub-system of a larger system.

Software Systems

A software system is composed of interconnected components that are software


objects. As with all systems a component may be a sub-system, i.e. a software system
in its own right. Most of us have to deal with complex systems all the time, for example
modern operating systems. They are complex, respond in many ways to many
unpredictably ordered inputs and should, in principle, continue to run once started.

Consider the Windows 95 (or Windows 98 or NT) software systems. One software
system is the operating system itself and any application programs that are also running
– such as word processors and web browsers. Each application program is itself a sub-
system containing its own set of objects. One form of behaviour exhibited by operating
systems is that they can create new and destroy existing instances of application
programs.

We consider software systems, and even simple computer programs, to be a network of


software objects. Humans express software using a programming language, so to

A note on spelling: In British English computer programs are spelt with a single
‘m’ and no ‘e’, whereas all other kinds of programme, such as television
programmes and programmes of study or events etc. are all spelt with ‘mme’.

A computer program can also be though of as an object itself. For example, a compiled
Windows 98 program (i.e. a file with a ‘.exe’ extension to its name) can be thought of as
a component object of of the system that is the Window operating system. This ‘exe-file’
object responds to messages sent to it, such as keypresses, mouse clicks and menu
item selections. It has a set of internal data it stores and operates on, and it sends
replies to messages received. In fact, for many parts of Windows, this is quite an
accurate description.

Systems programs and systems programmers – a possible source of confusion

Different computer programs do different things. A common way to classify software is


whether they are applications or system programs. However, in the use of the term
‘system’ here is not in the general way a system has been described earlier in this unit.
When the term ‘system’ is used to refer to a system program or systems programmer
the reference is to the software that is closely related to the operating system of a
particular computer. For example, the Windows 95 disk formatting software is a systems
program; it is not an example of the type of system we are most interested in.
(Unfortunately, the world of computing and software development is full of such
confusing terms.)

So system programs perform tasks that are inherently to do with the operating system
(parts of the system like computer viruses, sound volume, window and memory
management). Examples of system programs include: background virus checker,
soundcard volume controller, window managers, print manager, process scheduler,
backup utility

An application program (often just called an application) is usually short running and
helps the user perform a task not-directly related to a particular computer system.
Examples include: writing a letter in a word processor, playing a game, calculating an
invoice in a spreadsheet, searching for information in a database.

By long running it is meant that system software tends to be started when the computer
is switched on, and may run continuously until the computer is switched off. Or certainly
system software might run for a longer period than when the user starts and terminates
one or more applications (e.g. imaging printing a 1000-page book, the user could do
tasks with many different applications while the print manager ensures pages are sent
to the printer regularly). By short running it is meant that an application might be started
up halfway through a computer session, used for, say, 5 minutes and then terminated
when the user decides to do some other task. Application programs are so called since
they allow the user to ‘apply’ the computer to help perform some real-world task.

In the same way that programs are categorised into systems programs and application
programs, the programmers of such software are also categorised, i.e. into systems
programmers and application programmers.

Computer programming languages

Object-oriented programming languages, such as Java, allow computer systems and


computer programs to be conceptualised and worked with in a flexible and powerful
way.

At the processor level (i.e. machine code languages) many thousands (sometimes
hundreds of thousands) of instructions must be executed in any useful piece of
software, but high-level languages that are more suited to human expression are used
so we have to write orders of magnitude fewer ‘instructions’. With object-oriented
programming languages and their class libraries, by reusing or extending what is in the
libraries we write even fewer instructions that with traditional high level programming
languages such as Pascal.

Writing simple pieces of software can be straightforward – even easy, and fun.
However, when pieces of software become large or have to fit into a complicated
system, complexity becomes hard to deal with. In an introductory course like this
module, the examples will often be small and so not representative of full software
development. However, occasionally you may be asked to examine more complex
software. Indeed, as you explore Java and its classes you will have to get used to trying
to learn about pieces of a whole that nobody can fully understand. This is what makes
software development both hard and exciting!

A fundamental problem in software development is making a match between the


‘declarative’ knowledge that people have (i.e. knowing what behaviour is required of a
system) to the ‘procedural’ knowledge of the computer (i.e. knowing how to do
something). The development of techniques to assist the translation between
declarative and procedural knowledge is one of the major advances in the software
industry in the last twenty years or so. Object technology has made a significant
contribution here. It encourages a declarative approach using procedural techniques for
the detail of how to implement behaviour.
Software development activities

Software systems do not come from nowhere, and computer programmers do not
simply sit down at a computer and start writing code. Each software system goes
through its own life cycle. Although every systems life cycle is unique, there are certain
activities that tend to take place in some form for most systems.

There are different models of software life cycles, which are not a topic covered by this
module. Such models describe, or prescribe, both the activities and the sequence(s) in
which the activities take place. The summary of activities below is provided as some
useful background. In the case of object-oriented systems development, often activities
are repeated in a cyclic fashion, since problems/limitations of models may not be
identified until the design or implementation stages. Or perhaps the system users, when
presented with prototypes of systems identify new features of their real world system
that need to be integrated into the software system model and design.

Examples of activities occurring is software systems lifecycles might include:

 analysis and modelling


 system design
 implementation
 testing and evaluation
 maintenance and enhancement

Analysis and modelling

An analyst or team of analysts performed a study of the real world system that a
computer system is to be developed to support. There may be an existing real world
system, there may also be an existing computer system, or the project may be the
development of a new computer system to support some new department or
organisation that does not exist at present. One important task in modelling is the
identification of the boundaries of the system to be modelled and what the system is to
include. Models are created (for any existing, and the new, system), based on analysis
of the data, tasks, communication etc. between those components identified as included
in the new system, and those outside.

Analysis and modelling involve activities where you try to concentrate on certain more,
or less, abstract views of the system and to avoid making assumptions about detail. So
analysis is what we do when we try to produce a model of a system free of any internal
technology. The enclosing system context may set technology constraints; for example,
automatic teller machine (cash point) software may have to be analysed in a context of
current machines and cards with magnetic stripes. Hence you don't have choices during
analysis, but you do at the next level down (in terms of detail and precision), and this is
called design.

System design
Based on some form of model and analysis, a design for the computer system can be
created. Such a design is often, but not always, focused by having made the choice of
programming language that the system is to be implemented in.

Implementation

A system design is implemented in a particular programming language (or several, for


complex systems). Part of a system implementation may involve integrating existing
computer sub-systems, and perhaps designing communication with external computer
systems and databases. Often one or more prototypes are implemented, to test ideas,
and perhaps to provide users to help in an improvement of the system modelling and
design. Often the term ‘coding’ is used to describe the activity of actually writing
computer programs.

A note on terminology

The term ‘programming’ is usually used in a general way, to describe all the
activities of software development. One part of programming a computer system
is the actual coding during implementation.

Testing and evaluation

Parts of, or the complete, implemented system are tested with real, and imaginary data.
These software (sub)systems can also be tested by the real world users, or perhaps
staff playing the roles of the eventual real world system users. The results of testing and
evaluation often direct the software development team to perform one or more previous
activities again. In such a way systems may be developed in an incremental fashion.

Maintenance and enhancement

Studies have shown that at least 70% of the costs associated with software projects are
incurred after the system has been deployed. The work done after deployment is
usually called maintenance. However, this term is misleading as it suggests that the
software might degrade in functionality or performance if not ‘maintained’. Software is
not like mechanical artefacts that perform less well if not, for example, cleaned and
oiled. While software maintenance is most often associated with fixing bugs, in reality
the major difficulties and costs are encountered when changes or enhancements must
be made. Object technology is supposed to help here because it allows software to be
better designed and implemented to simulate that world it is designed for. Hence, when
changes appear in the real world, such as changes in tax laws or network
arrangements, the software can be straightforwardly changed or enhanced.

In the case of object-oriented systems development, the modelling, design and


implementation are performed from an object technology perspective. The various
techniques and programming languages of object technology should help in all these
aspects of software development.
Computers and Software Systems Activities

Activity 1 – Installing jdk1.3 and TextPad 4.5

Activity 2 – Set up the Unit 1 Example Applications

Activity 3 – Interacting with objects in a small software system

Object-oriented systems

Please note that this overview briefly presents all the major concepts of object
technology. The subsections and related activities that follow slowly introduce each of
these concepts in detail with examples and learning tasks. You may wish to evaluate
the extent of your understanding of object concepts by re-reading this overview to see
how many of the concepts you understand as you progress through the unit learning
materials. An important learning objective for this unit is to understand, and demonstrate
in the practical activities, these concepts behind object-oriented systems.

Object concepts provide an elegant and powerful way to view, reason about, model and
program systems.

Overview of object concepts

Object concepts are not limited to computer programming. Fundamentally, object


concepts provide a framework for modelling in terms of the objects which make up a
system. Other, more traditional, modelling techniques have concentrated on either the
data managed by a system (e.g. data flow modelling) or on the operations the system
carries out (e.g. functional decomposition). Object-oriented analysis and design allows
both data and operations to be modelled (encapsulated) together, in a way that can be
used to design and implement computer programs that preserve and exploit such an
encapsulated view of systems and their component objects.

The fundamental concept in all object-oriented technologies is the object. At a high level
of abstraction an object is a software component that has:

 behaviour: an object can do work


 state: an object can remember aspects of its work
 individuality: an object can be distinguished from other objects without having to
look at any part of its state – i.e. each object can be referred to via an individual
identifier
An object is an instance of a class. There may be many objects all based on the same
class.

To imagine an instance of a class, consider the Notepad application that is provided as


an accessory in Windows operating systems. (Whether or not Notepad is object-
oriented does not matter, it behaves in an object-oriented manner.) You can imagine
starting Notepad a number of times (see later activity) Each time you start an instance
of Notepad is like creating an object of the class Notepad. Each instance is different
from another although we as humans can probably only tell the difference by what is
written on the pad or by the name we give to a note pad document.

An important part of analysing what classes might be involved in an object-oriented


system also involves analysing what responsibilities objects of a class might have and
how they might collaborate with objects of other classes. This should become apparent
as you go through the module.

The execution of software systems

As it executes an object-oriented system creates and destroys objects. (You can


imagine Notepad objects being created as you start the accessory application and being
destroyed when you close it.) Since each object takes up a portion of a computer’s
resources, objects are often destroyed when no longer needed while the program goes
on to perform other tasks. Ultimately when a program terminates, the operating system
tidies up its resources by destroying any objects left by the program. Java, like
Smalltalk, but unlike C++, takes care of the recycling of resources for you by a process
called garbage collection. Roughly, the way this works is that resources required for an
object – the information it holds and the behaviour it provides – are reclaimed when all
other objects no longer use it. For example, in a banking system the software would
have to remember the objects that represented accounts and all of these would use
physical storage. When an account is closed the object representing it does not need to
remembered anymore and in the background Java arranges for its resources to be
collected as garbage.

Objects send messages to each other to cause particular behaviour to occur.


Associated with the concept of a message are those of the objects that are the sender
and receiver of the message. An object has a set of messages that it knows how to
respond to called its protocol. An object will only evoke some behaviour for valid
messages it receives – i.e. messages that are within its protocol. The object that is a
receiver of a message usually sends a reply (answer) back to the sender of the
message.

The behaviour of an object will vary depending on its state at the time of receiving a
message.
Specification of software systems

A slightly different form of language is used when modelling and specifying what a
system should do. Each object’s behaviour can be defined in terms of a set of
operations it provides to other objects to use. The information for which an object should
be responsible is defined as a set of attributes (sometimes called properties). As we
shall see, both these terms tend to become mixed up with terms more properly used
when coding.

Inheritance and polymorphism

The definition of a class of objects can be a specialisation of some existing class of


objects – i.e. the new, more specific class of objects can inherit attributes and
operations from its (parent) superclass.

Associated with inheritance is the idea of polymorphism by which is objects of different


classes can receive the same message that represents different behaviour. Such a
feature of a system allows great flexibility, since new behaviour can be easily added to a
system at a later date, with much of the existing system requiring no changes. Also new
types of objects can be added to a system. (See additional material in Extend section if
you want to know more.)

Among the virtues of object technology is the possibility of maximising continuity


between that part of the real world a computer system is simulating, an analysis model
of it, a design model, and implementation. With such continuity, one increases the
chance of systems being correct (i.e. able to do what they were intended to do). The
communication between various specialists involved, from domain expert to
programmer is also increased. The actual level of software reuse is often less that one
might hope for, but there is no doubt that it is important to develop a vast and growing
class library to reuse or specialise. Most cases where software can be reused is through
the development of more specialised forms of existing objects – i.e. existing objects are
extended (specialised).

Object-oriented software development processes

In a short course like this module we cannot cover all the important ideas relevant to the
subject of object-oriented software development. One idea that needs to be recognised
but which we can safely ignore because of the straightforward software we will work
with is that of the type of objects. This defines a set of objects that have the same
interface, the same protocol of messages that they will respond to. (In Java you must be
careful distinguish between interface that specify sets of messages and user interfaces.)
We have no choice about the types involved in a situation, they are there waiting to be
uncovered. Types are what we look for during analysis of what needs to be designed
and coded. Classes are what we use when designing and coding object-oriented
software. We have choice when selecting classes. Fortunately in many situations this is
not an important distinction and types are implemented as classes, so we can just talk
about classes.

A simple way of coming up with a list of potential classes is to consider the nouns that
appear in any description of what is required of a system. Examining the verbs can help
determine behaviour by suggesting the names of messages that instances of classes
should receive. Almost always the list of classes you may come up with will be too
large. You have to discard many potential classes. The ones you discard are those
which have little or no behaviour. As a general rule you can discard classes whose only
purpose is to hold some value for another class.

Usually, identifying classes like this is no more than identifying all the values of some
attribute for another class. So in considering, for example, a class to model car
registration, you might find descriptions of estate cars, hatchbacks, compact cars and
three-wheeled cars and might decide that you need classes EstateCar, HatchBack,
ThreeWheeler. If there is a need to record this information but it does not affect
registration behaviour, then these classes are no more than a list of attribute values,
one of which will be assigned to a Car object.

Although the system being constructed is rarely represented as one of its own objects,
there may be a class with a single instance that plays a pivotal role organising how the
other objects in the system work.

Object technology concept map

The concept map below represents important concepts in object technology. You will
find definitions of each of them in this and other units. After completing the module your
glossary will have entries for each of these concepts.
Activity 4 – Looking up glossary entries
Activity 5 – Software System Messages and multiple Instances
Activity 6 – Following concept map hyperlinks to glossary

Now do Review Questions 1 – 5

Abstraction

By abstraction it is meant that a person modelling a system in object-oriented terms can


avoid having to worry about the details of computer memory and instructions, and how a
particular piece of data might be represented on a computer. It is possible to model and
reason about a system in terms that are meaningful in the real world, so for example
each of the following can be modelled and talked about in object-oriented terms:

customer
bank account
space invader
mortgage
student
qualification

The modelling of system components and behaviour at an abstract level does not mean
that we are being vague – object-oriented models are used as the basis for program
design and implementation. However, object-oriented analysis and design does mean
that some of the more precise details can be put to one side until a later, probably
design, stage takes place.

Classes and objects

A class is a way of describing a category of objects that can be viewed as similar in


some way. For example, a public library might have on its shelves the following objects:

 a copy of the novel ‘War and Piece’


 a copy of the text book ‘Java How to Program’
 a copy of the CD album ‘Yellow Submarine’ by the Beatles

We can describe all these objects as instances of the class LibraryItem. They have
many things in common. All these objects have similar attributes, such as:

 title, author(s) or composer(s), loan status, loan duration, due date, loan fee (books
might be free, but CDs might be loaned at a charge of 50p per week), late return
charge

These objects also have similar operations, such as:

 set loan status to ‘on loan’ or ‘on shelves’


 tell us the ‘loan fee’ value
 set the ‘due date’ to be the first working day after the current date plus the ‘loan
duration’

Warning: we are using the value of certain attributes such as a book title to distinguish
between book instances because we are human and can distinguish using content. But
we can also identify two books of identical title and content, like two copies of the
famous object technology book Design Patterns. Always remember that software
objects have individual identity.
Of course, modelling is a personal activity, and different people (or teams) may come up
with different classes, attributes and operations.

There are differences between each of the three LibraryItem objects listed above.
However, they are more similar to one another than they are to, say, a hat-stand or a
cheese sandwich or a bank account! Furthermore, it makes sense for them to be
modelled as objects that are instances of the same class.

Note that, by convention, the names of classes are written with an initial capital letter
(e.g. Library, not library) and this convention is followed in this module.

In fact, when writing in the Java programming language, spaces are not
permitted in the names of classes, so in a Java program we might use the class
name LibraryItem.

Such coding conventions are considered in the module units that follow.

Object-oriented analysis and design the process of breaking down a system (for
example the stock department of a DIY shop) into the classes it contains, and finding
how these classes are related. It also involves modelling how do decide when objects of
each class will need to be created and destroyed by computer programs.

Object-oriented programming is the process of writing sections of program that


correspond to each class.

Kinds of real-world classes

Classes are usually of two different kinds, either classes of physical, real world objects
that we wish to model on a computer (such as: Car, House, LibraryItem etc.) or
classes of concepts that we wish to model on computer (such as:BankAccount, Job,
StudyModule etc.).

It is usual when modelling and implementing computer programs for a system to find
examples of both types of class. The difference between the two is that objects of real
world classes are physical, e.g. you could kick a particular car owned by Jenny
Jameson, or throw a stone through the window of the house object at 31, Pyramid Lane,
Cityville. The objects of concept classes, such as John Smith’s bank account, or the
module INT4120 are not physical things, although they too can be modelled and
programmed and used as part of a computer system.

A note on the classes you will meet: often you will find that the objects from certain
classes are solely responsible for interacting with the 'real' (i.e. non-software) world
which we inhabit – for example, objects for windows, buttons, etc. You will create and
use such objects from the Java library of classes. Other objects are created from
classes you have identified a need for and programmed. Typically these are to do with
some problem area, some domain. Hence the classes are called domain classes.
Where the domain is one of business, you can see that they will have to somehow
reflect the rules by which the business under consideration works. For example, if you
have a banking business as the domain, any class that represents what happens with
bank accounts, will have to reflect banking practices.

Classes and Objects: Summary

We can summarise object concepts as follows:

 Classes structure and organise a program


 Classes are self-contained and autonomous
 There may be many objects of the same class
 A large program will have many classes, and many objects of each class
 A convention followed in this module is that class names are spelt with the first
letter capitalised
 There are both classes of real world things and classes of concepts
 Domain classes are those reflecting the real world system concepts, while other
classes will solely be responsible for interaction

Now do Review Questions 6 – 10

Encapsulation

An important principle of object-oriented analysis and design is how both the attributes
(data) and operations of objects are modeled together. This makes object-oriented
modeling more natural than many other modeling techniques, since it allows a modeler
to model the things we know and wish to record about a class of objects (e.g. bank
account balance) alongside the actions we need to be able to perform on such objects
(e.g. open new account, deposit money, withdraw money, set up standing order). The
term encapsulation is used to describe this feature of object technologies.

Below is the Java code for a simple, bank account class of objects called
CurrentAccount. The details of the Java are not important for this example, however
what is hopefully clear is the way both the data (balance) and the operations (add coins,
remove coins) are modelled together in the single class CurrentAccount.
Comments in Java code

Note that any line beginning with "//" is a Java comment. The whole line is ignored by
Java, and in most cases comments are solely added to program listings for the
important purpose of presenting useful comments to help a human understand the
program.

Thus lines such as "// current balance of CurrentAccount" do not effect the class
behaviour, but does make the Java code much easier to understand.

class CurrentAccount{
// current balance of CurrentAccount
private float balance;
void CurrentAccount()
{ //create new bank account with 0 balance
...}
void debit( float amount )
{ // subtract value of coins from balance
// error if try to take out more than balance
...}
float getBalance ()
{ // return value of balance
...}
float setBalance ( float amount )
{ // return value of balance
// (maybe with additional behaviour)
...}
} // end of class CurrentAccount

Notice for this example, how there are separate ‘get’ and ‘set’ methods, called accessor
methods that control access to the balance attribute. Thus encapsulated in this class is
the feature that the value of the balance attribute is different depending on the operation
wishing to retrieve the value. In the example, the balance for normal transactions would
be whatever value is stored in the object. However, since a charge is made when an
account is closed, the value of the balance attribute returned by the operation
getBalancee() has a charge deducted from it.

Classes and Objects and Encapsulation: Activities

Activity 7 – classes and objects

Activity 8 – Encapsulation of attributes and operations

State
The state of an object is the set of values of all its attributes at a point in time. At
different points in time an object may have different states. The concept of state is
important, since the way an object behaves to a message will depend on its state at the
time the message is received.

Examples of a software object's state include the following:

 whether the window for a document (or application) is maximised or minimised


 whether an email application is connected on not
 whether a calculator program is expecting a number to be typed, or an operator
key such as +
 the balance of a bank account object
 the telephone number of a client object

Attributes

Part of the definition of a class is the set of attributes for each object of the class. An
attribute is some feature of an object that we wish to model. Examples of attributes for
the LibraryItem class might be:

title
author(s)
publisher
loan status
borrower
loan duration
due date
loan fee
late return charge

An object of a class will have values for each of these attributes. For example the object
for the copy of ‘Java How to Program’ in our imaginary public library might have the
following values for the above attributes:

o an object of LibraryItem class with title ‘Java How to Program’

Attribute Value

title Java How to Program

author(s) H. M. Deitel
P. J. Deitel

publisher Prentice-Hall
International, Inc.
loan status on loan

borrower Jim Jones

loan duration 2 weeks

due date 10 / Sep / 1999

loan fee free

late return charge 0.05 pounds per day

A ‘Yellow Submarine’ CD object will have different values for its attributes, for example:

o an object of LibraryItem class with title ‘Yellow Submarine’

Attribute Value

title Yellow Submarine

author(s) The Beatles

publisher K-Tel recordings

loan status on shelf

borrower

loan duration

due date

loan fee 0.50 pounds per week

late return charge 0.25 pounds per day

Notice that in the above example, some attributes are empty. When writing computer
programs to work with classes and objects, we must have some way to both store
values for the attributes of an object of a class, and also to record when we have no
value for an attribute.

(And remember, the attributes do not identify the objects in question.)


Taking the example Novel class described above, what attributes does an instance of
Novel have? Here are some possibilities: author, date of writing, date of
publication, number of pages, text. All these things may be information a Novel
object might be responsible for. For a particular novel (that is, for an object of the Novel
class) the attributes will have values. For example, you might expect an instance of
Novel that had the value of its title ‘Great Expectations’ to have the value ‘Charles
Dickens’ for its author attribute.

What operations does the Novel class have? That is, what names might we use to
describe its behaviour. This rather depends on the application. The things that a library
does with a novel will not be the same as, say, a publisher.

These ideas may seem a bit strange at first; you will not need to worry about them too
much at first, as your programs will not be complex enough to need more than one
class. However, when you start writing programs that have graphical user interfaces,
you will need to ensure you have grasped the idea. In Java, user interface elements like
buttons, windows, and menus are objects of the class Button, Window and Menu
respectively.

A note on the values stored in the implementation of attributes

In a pure object-oriented language such as Smalltalk a value is a reference to an object.


But in Java, which does not implement all object concepts in a ‘pure’ way, the
implemented value of an attribute might be an object reference, or it might be a primitive
value (such as an integer, or boolean true/false value).

Such questions become important when one begins to wish to implement object models
in a particular programming language.

Operations

A class is defined in terms of its attributes and its operations. An operation is some
action an object of the class performs – the behaviour of an object is made up of the
particular operations it executes.

Staying with the example of the class LibraryItem, operations that might be defined for
an object of the class include:

 setting the loan status attribute to the value ‘on loan’ or ‘on shelves’
 tell us the ‘loan fee’ value (i.e. the object tells another object/part of the system
the value of one of its attributes)
 set the ‘due date’ (e.g. to be the first working day after the current date plus the
‘loan duration’)

Operations are implemented as methods in programming languages such as Java.

Controlling state change

The state of an object is often carefully controlled by only allowing certain variables of
an object to be accessed by the object's own ‘get’ and ‘set’ methods. This prevents
some other object changing an object's attribute to some invalid or meaningless value.
For example:

as a part of a picture of a snowman a drawing application might have a Circle


object, and wish to make the radius of the circle smaller each time some button is
clicked. If the application were to simply subtract a value (say 50 pixels) from the
value of the object's radius attribute each time the button were clicked, after
enough clicks the Circle object would have a negative radius – clearly not
something a robust program should allow to happen.

This can be avoided by making the radius attribute only changeable by the
object itself, and requiring other objects (e.g. the application object) to request a
change of the radius via a set message. A Circle object can then the setRadius()
operation defined carefully so that it will never set the radius to less than 0 (or
some reasonable value for the system).

State changes and Class hierarchies: Activities

Activity 9 – Methods that access an object's attributes

Activity 10 – Methods that access an object’s attributes

Now do Review Questions 11 – 15

Inheritance

A significant strength of object technology is the ability to reuse classes and objects that
have been previously defined. One way this is possible is when a new class needs to be
modeled that is an extension (or specialization) of some class that has already been
modeled (and perhaps implemented). A class that acts as a ‘parent’ for a more
specialized class is called a superclass.
A class defined in terms of an existing class only needs to define any new (or different)
attributes or operations -- by default it will inherit all the attributes and operations from
its superclass.

Class hierarchies

When a new class is defined in terms of an existing class, it automatically inherits all the
attributes and operations of its parent. The parent class is called the direct superclass,
and of course it too may have been defined in terms of another class. The new class
defined as a specialisation of its direct superclass is called a subclass. A subclass may
have many superclasses, i.e. its direct superclass, and then the direct superclass's
direct superclass and so on.

In such a way a class hierarchy is built. Class hierarchies can be shallow (just 2 or 3
levels of sub- and super-classes), or they can be very deep (10, 20 or even more levels
of sub- and super-classes.

A note on misleading terminology:

In the normal use of English language we tend to think of super as meaning more
and sub as meaning less. However, in the case of superclasses and subclasses
the meanings here the reverse -- since a subclass is an extension of some class.
When referring to object inheritance the prefixes "super" and "sub" simply mean
"higher" and "lower" in the class hierarchy.

A particular level of a class hierarchies can also be either narrow (whereby a class has
only a few subclasses) or very broad (whereby a class has many subclasses).

We might create the following hierarchy of classes for our public library:

LibraryItem
TextItem
FictionText
NonFictionText
Recording
Video
AudioCassette
CD
AudioCD
CDROM
DVD

In this example we have at the top of the hierarchy the superclass LibraryItem. This
superclass has two subclasses: TextItem and Recording.

The class TextItem is itself the superclass of its subclasses FictionText and
NonFictionText.
The class FictionText has the direct superclass TestItem. It also has a superclass
LibraryItem. We can also say the FictionText is a subclass of LibraryItem , as well as
being a subclass of TextItem. This is the reason for using the more precise terms direct
superclass and direct subclass in certain situations. However, since most of the time it
is the direct superclasses and subclasses that are referred to, the term direct is not also
used, so a reader of a book or model or program documentation may have to infer or
seek clarification as to whether a direct superclass or subclass was intended when just
the phrase superclass or subclass is used.

We could define our LibraryItem class to have operations and attributes that are
common to all kinds of library item, then define particular operations and attributes for
each subclass. For example

 Record objects might have extra totalDuration and numberOfTrack attributes.


 FictionText objects might have an extra genre attribute and operation
setRebindingDate()

By the way, some classes never have their own instances, only subclasses. Such
classes are called abstract. The class LibraryItem is such an abstract class — one
would never have an instance of LibraryItem, but one would have an instance of some
subclass of LibraryItem. Another example of an abstract class is Bird — any
particular bird is not an instance of the class Bird directly, it is an instance of some
subclass, such as Sparrow, Blackbird, BaldEagle etc.

Overriding methods

As well as a subclass adding new attributes and operations for the specialised class it
represents, it may be that the subclass needs to perform some different actions for an
operation already defined and inherited by a superclass. In such cases a new operation
is defined in the subclass, that overrides the method defined by one of its superclasses.

Messages

The objects making up a system communicate by sending messages to each other. For
example, a system might send a closeAccount() message to a SavingsAccount object
of a bank computer system for a particular client’s bank account.

An object receiving a valid message will respond by performing some operation(s): i.e.
the object will exhibit some behaviour. For example, after receiving the closeAccount()
message a SavingsAccount object might send a message to request a cheque be sent to the
client for the balance, set its balance to zero and then disable any more transactions to
be processed for the account.
Messages with arguments

Many operations are designed to be as general purpose as possible. One way this is
achieved is by having an operation that can change what it does according to some
values passed to it along as part of a message. For example, an operation to increase
the balance of a bank account would probably be designed to expect a particular value
of how much to deposit. The sending of such a message might be in the form:

o send message depositMoney( 101.54 ) to object bankAccount123

In the above example a particular object (bank account number 123) is to be credited
with £101.54. The value "101.54" is called an argument (also sometime called a
parameter). Messages can include zero, one or many arguments. Other example of
possible message with arguments include:

o send message setRadius( 200 ) to object circle1


o send message setWindowPosition( 100, 200 ) to object
notepadApplication1
o send message retrieveHTMLPage("www.mdx.ac.uk/index.HTML") to object
browserWindow2

You actually have a lot of experience of sending messages with arguments through
your interaction with almost all Windows programs. For example, In a text editor or word
processor when you wish to save a file with a new name and select the ‘Save File As’
menu choice, you are presented with a dialog window in which you enter/choose the file
name and location. The dialog window object will then send a message with your
choices (as arguments) back to the application, and the application will write the file to
disk. In the figure below a file is being saved from the Notepad accessory application:
A reply such as the following is returned to the application from this file dialogue object:

return to object notepadApplication1


the reply ["c:\temp\", "menu1", textDocument]

Messages and Events: Activities

Activity 11 – Sending simple messages to a Circle object

Object-oriented programming languages

Different realisations of object concepts as programming languages

The basic ideas of object technology can be (and are) realised in different ways. As
usual with the implementation of any ideas, compromises are needed. Two computer
programming languages which implement object concepts in different ways are
Smalltalk and Java.

In Smalltalk there are only objects, messages and variables, and they work entirely
uniformly. In Smalltalk, even classes are available as objects. In Smalltalk, all classes
can be subclassed, and all inherited methods can be overridden. In Java, primitive
types and operations are provided, so there are ways other than objects to represent
information. In Java, classes or methods can be marked as final and so not subclassed
or overridden.

Influence of choice of programming language

Recalling the list of possible activities occurring in the life cycle of a software system,
the work that is done before coding is a suitable abstraction of what happens at coding.
In this module, of course, we concentrate on an account of object technology that suits
Java, however, you need to be aware that what we describe in the rest of this module is
not the only way to carry out object-oriented software development.

Now do Review Questions 16 – 19

Activity 1 – Installing jdk1.3 and TextPad 4.5


To use TextPad on your machine for editing, compiling and executing Java programs,
you will need to install both the TextPad software and the JDK (Java Development Kit)
from the Global Campus Installation CD-ROM. Follow these steps:

(i) The JDK is installed first. When you are prompted for a Destination Folder, note the
name of the folder. On the standard installation it is \jdk1.3 . Remember also the disk
volume (e.g. C: or D:). For this tutorial we will use D:\jdk1.3 as the JDK folder.

(ii) Now save the JAVA DOCUMENTATION onto the same disk volume as the JDK
folder. Again, make a note of the folder path and name.

(iii) Now you are ready to install TextPad. Follow the instructions on the CD-ROM and/or
the WebCT Bulletin Board for this module.

Activity 2 – Set up the Unit 1 Example Applications

Some of the later activities in this unit involve using the applications "TwoCircles",
"CircleSquare", "GetSetMessages" and "SimpleMessages". This activity runs a program
to load a library of routines onto your computer to allow you to use the applications for
this unit.

There are 3 steps you need to follow:

(1) Close all other applications apart from this web browser.
(2) Using the Windows Explorer find the executable file snjrt20.exe and run this file.
(3) Restart your computer.

Once your computer has restarted you should then be able to use the
applications referred to in some of the following activities for this unit.

Note:

If you have difficulties installing snjrt20.exe ask your Learning Support


Centre for advice, and inform your tutor.'

Activity 3 – Interacting with objects in a small software system

Run the TwoCircles application

A window should open, presenting at the top, buttons to choose either "circle1" or
"circle2", on the left a set of buttons and on the right a drawing area showing two small,
black circles. Your computer should look similar to the screen shot in the figure below
(although below we see that circle1 has been made larger and its X-position changed):

By clicking on a button you will be sending a message to either circle1 or circle2 .


You can select which circle a message will be sent to by first clicking the radio (round)
button next to the object name circle1 or circle2 .

By clicking the appropriate message buttons perform the following tasks on the circle
object:

(1) make circle1 blue

(2) make circle2 red

(3) make circle1 small by setting its radius to 10

(4) make circle2 large by setting its radius to 50

(4) explore the other message buttons

Discussion of Activity 3 – Interacting with objects in a small software system

Interacting with objects in a small software system

This activity provides you with experience of seeing, and influencing how a software
system works. When reading through the overview of object concepts, refer back to this
program to see which concepts it provides examples of.
Notice also how it was necessary to know which circle to send messages to: each was
identified uniquely by referring to either circle1 or circle2.

Activity 4 – Looking up Glossary Entries

In the Computers section of this unit the following phrases have glossary entries:

 execute
 instructions
 system software
 machine code

(1) In your own words write a short definition for each of these phrases.

(2) Compare your definition to those of your colleagues in the class.

(3) Identify (and correct) any important conceptual differences between your definition
and the glossary entry

Discussion of Activity 4 – Looking up Glossary Entries

Looking up Glossary Entries

Such exercises as defining terms in your own words, then comparing your definition
with your colleagues or some other source can be an effective way of evaluating your
understanding of new concepts. It important to highlight differences between your
understanding and sources such as the glossary, since such differences are an
indication that you may need to study a topic in more detail to resolve conceptual
misunderstanding.

Activity 5 – Software System Messages and Multiple Instances

(1) Explore the concepts of different components of a software system communicating


via messages by running the Notepad text editor in the following way:

Cause one instance (i.e. window) of the Notepad editor to be run from the Start
menu.
To do this choose appropriate menu options from the Windows Start menu. The
actual options may vary a little from computer to computer – on a typical
Windows95 computer the menu choices are:

Start | Programs | Accessories | Notepad

(2) You have created one instance of the Notepad application object. Choose the same
Start menu choices again to create a second instance of the Notepad application.

Discussion of Activity 5 – Software System Messages and Multiple Instances

Software System Messages and Multiple Instances

(1) A new window should appear, running Notepad with a new, empty text file. By
choosing those menu choices the Start software object sent a message to the operating
system to run an application program. Running a program causes a number of things to
be done, such as allocating RAM memory for the program, allocating some of the
microprocessors time to execute the instructions of the application, and creating a new
window on screen so that the user can see what they are doing with their text document.

The new Notepad application started up is a software object. This object can respond to
messages the user sends (for example by pressing keys, or choosing items from the
application window’s menu bar). Also this Notepad object can send messages to other
software objects in the software system, for example choosing to print a text file, or
choosing to save a text file with a new name, causes the messages to be sent to other
software objects.

Choosing to print a text file makes the Notepad software object send a message to the
operating system’s print manager object. This will then cause the print manager to store
(queue) the file to be printed, and to attempt to communicate with the printer to print the
document when all previous documents waiting the print queue have been printed.

Choosing to save a text file causes a message to be sent to the disk software object,
causing communication between that object and the disk the file is to be saved onto.
These communications involve the contents of the text file being sent to the disk for
writing, and the disk sending back details of what has been written, for verification that
the correct file contents have been saved.

(2) As you can see, it is possible to have more than one instance of a software object
running at the same time. Windows has a template of the Notepad application, and can
create as many objects (instances of that template) as required – or a least until the
computer runs out of memory!
Activity 6 – Following concept map hyperlinks to glossary

(1) Choose a phrase (a ‘node’) from the object technology concept map and following its
link to its glossary entry.

(2) Follow the link back from the glossary entry to the object technology concept map.

(3) Follow the link from the glossary entry to a unit where the phrase is referred to.

Discussion of Activity 6 – Following concept map hyperlinks to glossary

Following concept map hyperlinks to glossary

You have explored the hyperlinked nature of the concept maps, and the links to and from
glossary entries to concept map nodes & units.

Activity 7 – Classes and objects

This activity asks you to place yourself in the shoes of a system modeler, by thinking up
examples of classes and objects that are instances of classes that are plausible for the
example systems.

(1) Suggest 3 or 4 classes that might be needed for the personnel department of a
university.

(2) Suggest 3 or 4 classes that might be needed for a supermarket system.

(3) Suggest 3 or 4 classes that might be needed for a bank system.

(4) Suggest 3 or 4 classes that might be needed for a hospital.

(5) Create 2 or 3 instances for each of your university classes.

(6) Create 2 or 3 examples of instances for each of your supermarket, bank and hospital
classes.

Discussion of Activity 7 – Classes and objects

Closses & Objects


(1) Classes for university personnel department. Your answer should list classes such
as the following:

Employee
Job
Department

(2) Classes for supermarket system. Your answer should list classes such as the
following:

Employee
Customer
Product
Supplier

(3) Classes for bank system. Your answer should list classes such as the following:

Employee
Customer
BankAccount
Transaction
Mortgage

(4) Classes for hospital system. Your answer should list classes such as the following:

Nurse
Doctor
Patient
Ward
Operation
Disease

(5) Objects that are instances of university personnel system. Your answer should list
instances with typical attributes such as the following:

 class Employee: with name attribute values such as‘Fred Bloggs’, ‘Kostas
Karoulas’, ‘Jane Smith’, ‘Asim Udat’, ‘Neelam Patel’
 class Job: with jobFunction attribute values such as manager, cleaner, lecturer,
professor, administrator
 class Department: with departmentTitle attribute values such as ‘Computing
Science’, ‘Biology’, ‘Mechanical Engineering’, ‘Performing Arts’, ‘Social Science’

(6) Objects that are instances of your supermarket, bank and hospital classes. Your
answer ought to be similar to that for your objects of the university classes – as long as it
is easy to think of two or three examples of objects for each class, then the classes are
probably plausible ones.
Activity 8 – Encapsulation of attributes and operations

Note:
When you click on the link to MyTriangle.java the program will be automatically loaded
in the Kawa editor window. If you want to save it on your disk then give it the
name MyTriangle.java
Look at the listing of the Java program MyTriangle.java . Create a list of what you think
are the attributes and operations for this class MyTriangle .

Discussion of Activity 8 – Encapsulation of attributes and operations

Encapsulation of attributes and operations

Comments

Note that any line beginning with // is a Java comment. The whole line is ignored by
Java, and in most cases comments are solely added to program listings for the important
purpose of presenting useful comments to help a human understand the program.

Thus the lines // variables //, // methods // etc. do not effect the class behaviour,
but do make the Java code much easier to understand.

Attributes

After the line class MyTriangle there are a number of variables listed – remember, a
variable is the implementation of an attribute in a programming language. The list of
variables is:

int xPos;
int yPos;
int height;
int width;

Therefore each variable indicates to us that there is a corresponding attribute of the class.
Of course, there may also be additional attributes that are not stored as variables, but
computed when required, and retrieved through a ‘get’ access method.

The variables (xPos, yPos) are the implementation of the attributes for the (X, Y) position
of the bottom left of the triangle. The variables height and width are the implementation
of the attributes for the height and width of the triangle.

Note: The word int is a special Java command stating that the variable in question is an
integer (i.e. a whole number) – later units will present in detail the Java commands for
implementing attributes and operations.

Note: These values are in terms of the pixel on the screen.


Operations

There are 4 operations implemented in the class MyTriangle . These operations are
implemented in the Java methods:

public MyTriangle()
public void paint(Graphics g)
public int getWidth()
public void setWidth( int newWidth )

Don’t worry about the special Java commands public, void or Graphicsg. These four
operations perform the following:

 MyTriangle():creates and initialise an object that is a new instance of the class


MyTriangle
 paint(): will draw a triangle (on a given graphics ‘canvas’)
 getWidth(): returns the current width of the MyTriangle object
 setWidth( int newWidth ): sets the width of the MyTriangle object to the given
new value (providing the new value is > 0)

The MyTriangle class is a very simple one for illustration purposes. As a minimum, it
probably ought to also have attributes for colour of lines, colour to be filled in, width of
lines etc., and operations to set and get the height, and to set and get the X, Y position
of the triangle.

Listing of MyTriangle.java

import java.awt.*;
public class MyTriangle
{
// variables //
int xPos;
int yPos;
int height;
int width;
// methods //
public MyTriangle()
{
xPos = 50;
yPos = 50;
height = 20;
width = 10;
}
public void paint(Graphics g)
{
// set up co-ordinates of vertices
int bottom = yPos;
int top = yPos - height;
int left = xPos;
int right = xPos + width;
int middle = (int) ( xPos + (width / 2) );
// draw the lines of the triangle
g.drawLine(left, bottom, right, bottom);
g.drawLine(right, bottom, middle, top);
g.drawLine(middle, top, left, bottom);
}
public int getWidth()
{
return width;
}
public void setWidth( int newWidth )
{
if( newWidth > 0)
width = newWidth;
}
} // class

Activity 9 – Methods that access an object's attributes

Run the GetSetMessages application. A window should open, presenting on the left a set
of buttons to send messages to a MyCircle object and on the right a drawing area
showing a small, black circle. Your computer should look similar to the screen shot in
the figure below:

Perform the following tasks on the circle object by clicking the appropriate message
buttons:

(1) Find out X position of circle

(Hint: Use the message button int getX() )

Note: The X position is not the centre, but the top, left of a square defining the circle's
location

(2) set the X position of the circle to 200

(Hint: Use the message button setX( int ) )

(3) Find out the radius of the circle object

(4) Make the radius larger by scaling by a factor of 2


(5) Find out the radius again (now the circle is larger)

(6) Make the radius of the circle the same size as before doubling.

(Hint: Do this by scaling by a factor of 0.5)

(7) Try to make the radius zero by scaling by a factor of zero

Make a note of what happens – i.e. find out what the radius is after scaling by zero.

Discussion of Activity 9 – Methods that access an object's attributes

Methods that access an object's attributes

The tasks you have performed for this activity have involved sending messages and
receiving repliesfrom a MyCircle object. You have been attempting, via the invocation of
get and set access methods, to find out and change the state of the circle object.

By controlling access to the object variables via set() and get() and other methods such
as scale(), an object can maintain integrity by having the methods that change its state
not perform any inappropriate actions – in this case scale() checks to see the size of the
radius after applying the user's scaling factor, and if it would less than 1, sets the radius
to 1 (otherwise, once the circle had radius 0 it would never be able to be scaled to be any
larger number, and of course radii of -1 or less simply do not make sense).

(1) The int before the method name getX() tells us that this message will return to us
an integer value (i.e. a whole number). The empty parentheses tell us that we do not need
to provide any values when we send the message.

The reply send back to you is the value of the X position attribute of the object.

(2) The ( int ) in parentheses tells us that the setX message needs to be provided with
a single, integer value. This value is the new value we wish the X position of the circle to
become.

The int indicates a Java primitive type – see later units for details.

(3) This message results in a reply, in this case the reply is the value of the radius attribute
of the object.

(4) This can be done by sending a scale message provided with the value 2.

We can see the change in state (assuming our message was valid) by seeing a circle
redrawn on screen that is twice the size as before.
(5) We can confirm the change in the radius attribute of the circle object by sending
another getRadius()message.

The reply we are sent ought to be a value twice the size as before.

(6) The ( float ) part of the scale( float ) message button tells us that we need to provide
a parameter value with scale messages, and that the value can be any valid float number
(i.e. a decimal number).

The float indicates a Java primitive type – see later units for details.

Thus we are able to make the circle smaller by sending a scale message with a value
between 0 and 1, such as 0.5.

(7) The circle gets very small, but does not disappear.

After scaling by zero, we can see that in fact the radius has been set to 1, not 0, by
sending a getRadius message and viewing the reply returned to us.

The radius cannot be scaled below 1 for MyCircle objects because of the way scale
messages are implemented. The designer of this program decided that circle objects with
radius zero are not valid for this application, and so implemented the scale operation to
check the radius after scaling, and to set the radius to 1 if the value would have been
lower. This was a design decision made when the MyCricle class of objects was modelled
and designed. For a different system a modeller/designer might consider it appropriate to
allow radii of zero, or even negative radii, and would design and implement operations
like scale appropriately.

Activity 10 – Methods that access an object’s attributes

Looking at the class hierarchy for our library example , list all the superclasses and
subclasses, and all the direct superclasses and direct subclasses for classes Recording
and CD.

Answer the following questions:

(1) How many direct superclasses do classes Recording and CD have?

(2) How many superclasses do classes Recording and CD have?

(3) How many direct subclasses do classes Recording and CD have?

(4) How many subclasses do classes Recording and CD have?


(5) Explore the JavaDoc JDK documentation

Start up a browser and begin viewing the JavaDoc documentation.

The index.html file should look as similar to the figure below when opened:

and starting at the Object class, draw part of the class hierarchy. Write 4 sub-classes at
each level, even if there are more, otherwise the exercise could take a long time and a
lot of paper! Follow the hierarchy down for 3 levels, with Object as the top level.

Looking through JavaDoc, find a class that has very few subclasses.

(6) Looking again, find a class that has over 7 subclasses.

Discussion of Activity 10 – Methods that access an objects attributes

Methods that access an objects attributes


(1) In one form of object technology a class only has a single direct superclass. The class
hierarchy for out library example follows this approach of single inheritance. Therefore a
class will always have a maximum of one direct superclass.

The direct superclass of the class Recording is class LibraryItem.

The direct superclass of the class CD is Recording

(2) Although with single inheritance a class will have only one direct superclass, it may
have other superclasses, based on the direct superclasses of its direct superclass and so
on up the hierarchy.

The only superclass of class Recording is LibraryItem, because class LibraryItem is at


the top of our class hierarchy, and so has no direct superclass itself.

Class CD, however, has 2 superclasses: its direct superclass Recording, and also
LibraryItem. Class LibraryItem is a superclass of CD because it is a superclass of the
direct superclass of CD. Such relationships are much more easy to see looking at a
diagram of a class hierarchy than expressed in words (look back to the library example in
the content section of this unit).

It is the case that classes lower down in the class hierarchy have more superclasses than
classes higher in the hierarchy.

(3) It is possible for a class to have any number of direct subclasses (i.e. zero, one or
many). Class Recording has 4 direct subclasses:

Video
AudioCasstte
CD
DVD

Class CD has 2 direct subclasses of its own:

AudioCD
CDROM

(4) A class can have many subclasses, since it has its own direct subclasses, and also
any direct subclasses of its direct subclasses.

Class Recording has 6 subclasses, comprising its 4 direct subclasses (listed above), and
also the classes AudioCD and CDROM, since any subclasses of its direct subclasses are also
subclasses of Recording.

Class CyD has only 2 subclasses, which are its 2 direct subclasses AudioCD and CDROM .
This is because nether of its direct subclasses have any subclasses of their own.
It is the case that classes high up the class hierarchy have more subclasses that classes
lower down in the hierarchy.

(5) The Java language is based on a hierarchy of classes, each with subclasses and
superclasses. Some classes, near the top of the hierarchy, have few superclasses, others
lower down have many.

Classes lower down have fewer subclasses.

However, the number of direct superclasses or direct subclasses is not effected by a


classes position in its hierarchy.

An example of a Java class with few subclasses is java.awt.event.MouseAdapter which


has only a single subclass:

class javax.swing.ToolTipManager

(6) The class Object has no superclasses, since it is the top of the Java class hierarchy,
but has many subclasses, since every class lower in the hierarchy is, by definition of a
class hierarchy, a subclass of the topmost one.

An example of a class with more than 7 subclasses is class


javax.swing.AbstractButton:

class javax.swing.AbstractButton
class javax.swing.JButton
class javax.swing.JMenuItem
class javax.swing.JCheckBoxMenuItem
class javax.swing.JMenu
class javax.swing.JRadioButtonMenuItem
class javax.swing.JToggleButton
class javax.swing.JCheckBox
class javax.swing.JRadioButton

Class javax.swing.AbstractButton has 3 direct subclasses, and 2 of these have a


further 5 direct subclasses of their own, which makes a total of 8 subclasses for
javax.swing.AbstractButton.

Notice the convention, necessary for large software systems comprising many packages
of classes, that each class is prefixed with its package name.

Activity 11 – Sending simple messages to a Circle object

Run the "SimpleMessages" application. When the application runs it should create a
window (show in the diagram below), presenting on the left 4 buttons to press, and on
the right an area showing a small, black circle.
Make the circle exhibit the following behavior by sending appropriate messages to it:

1. set its color to red


2. set its color to blue
3. make the circle larger
4. make the circle smaller

Discussion of Activity 11 – Sending simple messages to a Circle object

Sending simple messages to a Circle object

Classes and objects

The application when run creates an object based on a class called MyCircle (you can
look at the Java code for this class if you wish, but you don’t need to understand it yet).
The Java code for this activity can be found at: SimpleMessages Java files

Protocol

The "SimpleMessages" application has been written so that it is only possible to send
messages to the MyCircle object that can be understood. MyCircle objects can
understand the following messages:

makeSmaller()
makeLarger()
setColorBlue()
setColorRed()

This means that each of the above messages is part of the protocol of MyCircle objects.

Messages, methods and behaviour

Each time you pressed a button, you sent a message (corresponding to the button’s
name) to the application’s MyCircle object. The circle object should have exhibited some
behaviour as it executed its method corresponding to the message sent.
Change of object state

The behaviour occurring when the MyCircle object executed its makeColorBlue() method
was for the object to change the part of its state that records its colour to blue. We became
aware of this change of state when the object redrew itself as a circle on screen in the
colour blue.

Likewise, when receiving makeSmaller() and makeLarger() messages, the object


changed the part of its state that records its size (i.e. its radius) to become larger or
smaller by some standard amount. We became aware of this change of state when the
object redrew itself as a circle on screen either larger or smaller that before we pressed
the message button.

Review Question 1

List some benefits that object orientation is thought to bring to the software development
process

Solution to Review Question 1

Object concepts are useful for:

 improving the quality of computer software production


 reducing the cost of computer software production
 understanding and designing complex systems

Review Question 2

How does one know which machine code a particular computer understands?

Solution to Review Question 2

A computer will only understand the machine code for the microprocessor that is its CPU,
so a PC with a Pentium II processor can only understand and execute Pentium II machine
code instructions and a PowerPC processor can only execute PowerPC machine codes.
Review Question 3

What are the components of a software system?

Solution to Review Question 3

Software objects.

Review Question 4

What is meant by the term ‘system’ when used before the words ‘program’ or
‘programmer’?

Solution to Review Question 4

As a general rule when the word ‘program’ or ‘programmer’ follows immediately after the
word ‘system’ then a software system such as Windows 95 or Linux, is being referred to.
In the absence of these words or some reference to a particular system, then the term
‘system’ should be considered to be a general term referring to a set of interconnected
components, broad enough to be used to describe a company department, a city, a
mechanical device such as a motor car, or a computer system.

Review Question 5

As a summary of object concepts fill in the blanks in the following paragraphs:

Object concepts involve classes and -------------that are instances of classes. Each
object is an instance of a------------- . A software system can create objects and destroy
objects.

The ---------------of an object is the set of data it remembers (stores). The behaviour of
an object depends on its state and the it receives. The -------------of an object is the
definition of all the messages the object can understand.

A class is defined by the encapsulation of the --------------and attributes of objects of the


class.
New classes can be defined as specialisations of existing classes. Thus classes can
exist in a class------------- , composed of superclasses and subclasses. A subclass
inherits the attributes and of -------------------its superclass.

--------------describes the situation when the same message sent to 2 or more different
objects results in the execution of different methods – it is made possible due to the
abstraction and of --------------------object-oriented approaches.

Solution to Review Question 5

Object concepts involve classes and objects that are instances of classes. Each object
is an instance of a class. A software system can create objects and destroy objects.

The state of an object is the set of data it remembers (stores). The behavior of an object
depends on its state and the messages it receives. The protocol of an object is the
definition of all the messages the object can understand.

A class is defined by the encapsulation of the operations and attributes of objects of the
class.

New classes can be defined as specializations of existing classes. Thus classes can exist
in a class hierarchy, composed of superclasses and subclasses. A subclass inherits the
attributes and operations of its superclass.

Polymorphism describes the situation when the same message sent to 2 or more
different objects results in the execution of different methods – it is made possible due to
the abstraction and inheritance of object-oriented approaches.

During the process of object-oriented software development you have to discard many
potential classes because they have little behavior.

Review Question 6

Write down how you might describe what an attribute is.

Solution to Review Question 6

Attributes are the different properties objects of a class have.


Review Question 7

What are operations?

Solution to Review Question 7

Operations are what a class does, or has done to it.

Review Question 8

What are the components of a software system?

Solution to Review Question 8

Software objects.

Review Question 9

Describe what objects do with messages.

Solution to Review Question 9

 objects send messages to each other


 an object receiving a message that it understands will exhibit an appropriate
behaviour
 some messages pass values along with the operation name, these values are
called arguments (also known as parameters)
Review Question 10

How do the software objects that comprise a software system interact?

Solution to Review Question 10

Answer: the objects communicate by sending messages to each other

Review Question 11

Give an example of a component of the Windows 95, 98 or NT software systems.

Solution to Review Question 11

Answer: any system program or application could be given as an example, such as


Notepad, MS Word, the print manager, the Start menu, a virus scanner etc.

Review Question 12

During Activity ‘SimpleMessages’ how was it that we became aware of the change of
state of the application’s MyCircle object? Were we directly observing the state of the
object?

Solution to Review Question 12

We saw the drawn circle on screen change colour or size.

>No, we weren’t directly observing the state of the object. An object’s state is the set of
values of all its object variables at any point in time. When the object changes it colour or
radius variables we became aware of this when the object redrew a circle in the new
colour or size in the application’s window.

We were seeing a view of the MyCircle object’s state.


Review Question 13

Define a program with reference to how it is like a network.

Solution to Review Question 13

A program can be though of as an object. For example, a compiled Windows 95 ‘.exe’


compiled program can be thought of as a component object of running in the system that
is the Window 95 operating system. This ‘.exe’ object responds to messages sent to it,
such as key presses, mouse clicks and menu item selections.

Review Question 14

Is a program like an object?

Solution to Review Question 14

A program can be though of as an object. For example, a compiled Windows 95 ‘.exe’


compiled program can be thought of as a component object of running in the system that
is the Window 95 operating system. This ‘.exe’ object responds to messages sent to it,
such as key presses, mouse clicks and menu item selections.

Review Question 15

What are the different meanings of the term ‘code’ ?

Solution to Review Question 15

Code can both refer to statements written in a high level programming languages such
as Java – i.e. the source file. It can also refer to the compiled machine code program –
i.e. the object file. Due to these two uses the term can be ambiguous. When writing the
term if there is any doubt as to whether the context is sufficient to make the meaning
clear, the phrase ‘object code’ or ‘source code’ ought be used in full.
Review Question 16

Name two computer object-oriented programming languages that implement object


concepts in different ways.

Solution to Review Question 16

Java and Smalltalk for example. The only type of value in Smalltalk is the object – so
every implementation of an operation, and every message argument is an object. In Java
non-object data types exist, such as arrays and primitive types like ‘float’ and ‘int’. Also,
in Smalltalk is it not possible to define a method of a class that cannot be overridden in
subclasses – such prevention of overriding and even subclassing is possible in Java.

Review Question 17

What is the difference between the terms ‘programming’ and ‘coding’?

Solution to Review Question 17

The term ‘coding’ refers to the activity of sitting at a computer writing programs in a some
computer programming language, such as Java. The term ‘programming’ is usually used
in a wide sense that ‘coding’, and may refer to all the stages and activities of software
development – analysis and modeling, program design, coding and testing.

Review Question 18

What categories of values do attributes have?

Solution to Review Question 18

From a pure object technology viewpoint each attribute value is a reference to an object.
However, when object models are implemented other kinds of value may actually be
implemented as software objects. For example, in Java a variable (the implementation of
an object attribute) can have values that are references to objects, or values that are
based on primitive (non-object) types such as integers and characters, or values that
store ordered sets of values (called arrays). However, some ‘pure’ object-oriented
computer programming languages implement object models such that all values of
attributes are (and have to be) references to objects.

Review Question 19

Some classes required to implement a system deal solely with user interaction (such as
buttons, menus etc.). What are these kinds of classes called? And what are the other
kind of classes called, that are to do with a particular problem area or real world
system?

Solution to Review Question 19

Classes required to implement a system deal solely with user interaction are often called
‘interface’ classes, or perhaps ‘windowing’ classes – such as Java’s AWT - Abstract
Windowing Toolkit package of classes. Classes that are to do with a particular problem
area or real world system are called ‘domain classes’ – such as those that might model
customers, stock items, clients etc.

Discussion Topics

There are many new concepts in this unit. If you want to discuss with your colleagues or
make comments about the concepts to them, use the on-line facilities.

Discussion topic: The choice of classes during object-oriented modeling

Do you think there should be a class for the sort of software system being built? So, for
example, when modelling what has to be coded for a car registration system, should
there be a class CarRegistrationSystem ?

Discussion Contribution

No, there should not be a class for the sort of software system being built. The
behavior of the system is provided by the behaviors of the objects that comprise it,
so you would not find, for example, that the CarRegistrationSystem itself had any
behavior.
Terminology

The table below illustrates the relationship between some of the terms used for object-
oriented modelling and the terms used when implementing object models in a
programming language like Java.

Modelling term Implementation term

class or type class

object

attribute

operation

set of variable values

behaviour

message

event

The careful use of terminology when referring to object concepts is important in


representing and communicating the model and implementation of a system. However,
since so many of the terms are closely related, and some encompass others (e.g.
"state" encompasses the values of variables that implement object attributes), you will
find programmers and programming text books often use terms in a way that leaves the
reader to infer whether it is a model or an implementation being discussed. For
example, a programmer might talk about an operation being executed when an object
receives a message, whereas it is actually a method that is executed, the method being
a sub-program that is the implementation of an operation.

Since much of this module is about the implementation of object technology systems in
the Java programming language, you will perhaps find it most important to understand
the particular statements in the Java language that implement its version of object
concepts (such as method , variable , class – these are introduced in the following
units). However, in this, and later modules, the learning materials will present examples
of object-oriented models, and so will use the modelling terms in their description.

In reading more widely you will encounter other terms. Many such other terms are
programming language specific. Other terms you may encounter include: member, field,
function. If you move on to object-oriented programming with some other language, an
important activity you'll need to undertake will be to learn the terminology of object
technology for the new language.

Extension Activity 1 – Completing the terminology table

Relation to other modules in Programme

BIS4222 Database management systems

There are excellent systems available to provide routine entry, management, and
analysis of large data sets. However, when complex database operations are required,
and are not catered for by standard software packages, then the ability to manipulate
databases using custom software becomes very apparent. This is particularly true when
large databases have to be integrated with other software systems. Java is a good
choice of programming language for this type of work; not because the language itself
has particular relevance to database management, but because of the broad support for
the JDBC (Java database connectivity) standard. Most commercial database engines
can be integrated with Java applications using JDBC. In addition, learning the object-
oriented philosophy that underlies the Java language will help students understand the
concepts of object-oriented databases.

CCM4223 Computer networks: operation and application

While little technical knowledge is required to set up a small computer network, design
and management of an efficient, complex corporate system requires a deeper technical
understanding of the computer and its operations. Learning to write computer programs
encourages the student to view the computer in a different way to that of an end user;
specifically it strips away the veneer of sophistication which modern graphical user
interfaces present their users with, and reveals the computer as a collection of hardware
devices under the control of software. Having made this conceptual jump, students will
be in a better position to understand the technical issues of complex networking.

BIS4225 Information systems management and strategy

The management of information systems often involves the management of software


development; most large IT departments employ programmers to implement and
integrate applications in ways that are not catered for by standard software packages.
The ability to manage the development of software projects is improved by a knowledge
of the development process itself. This, we suggest, can best be achieved by taking part
in software development as a programmer.

BIS4226 Internet commerce


Internet commerce is by its very nature an interactive activity; provision of this
interactivity requires software. Software is rapidly becoming available to support a range
of `typical' Internet commerce applications. As usual, however, non-standard
applications require custom software deveopment. BIS4226 includes an element of
Javascript programming; the knowledge of object orientation and Java programming
from INT4120 will be synergistic with this.

BIS4111 Information systems analysis and design

Programming is the development step that logically follows analysis and design. An
understanding of progamming will give the student a clearer idea of the outcome
towards which analysis and design are leading. In addition, the object-oriented design
and UML (unified modelling language) concepts which are taught in INT4120 from a
programming perspective will help to reinforce these concepts as they are taught in
BIS4111 from an analysis perspective.

BIS4127 Management support systems

The integration of INT4120 with this module can be understood in similar terms to its
integration with BIS4222. Essentially, while there are excellent software packages
available for performing standard decision support tasks, more complex systems can
often only be realized with the development of custom software.

CMT4130 design and evaluation of interactive systems

Certain theoretical principles may be applied to guide the development of systems


which encourage and simplify human interaction. However, the use of these principles
must be tempered with an understanding of what is practically achieveable with modern
software systems. An understanding of programming helps the professional to be aware
of what can, and can not, be implemented with existing technology, and what the costs
of implementation are likely to be.

BIS4992 postgraduate projects

In every group of MSc BIT students there will be a number who choose to undertake a
project that is based wholely or partly on software development. Recently such projects
have included

 an on-line, interactive Web site design tool for Internet service providers
 an interactive graphical front-end for a share trading database
 an on-line room booking system for hotels, with database integration

all of which were structured using object-oriented techniques and implemented in Java.
Reflection on Learning Experience

In your Learning Journal write up your experience of your learning on this unit. Say what
you thought was good or bad, what you had difficulty understanding, and how you
resolved your problems.

Polymorphism

Polymorphism is a feature of object-oriented systems that provides great flexibility and


consistency. Polymorphism refers to situations where the same message is sent to
objects from different classes, and different methods are executed. For example, any 2-
dimension shape such as a circle or square have an area, but the way they are
calculated differs from shape to shape.

Building on the concept of a programmer may wish to use a set of classes designed and
implemented as programs by someone else, but they may not wish to have to worry
about the complexity of the implementation of each class. If a programmer were writing
a 2D drawing program they might wish to use a library of pre-written classes for shapes,
each of which provides a "getArea()" method. The programmer can then happily send a
"getArea()" message to whichever graphic object he or she is wanting to work with,
secure in the knowledge that whichever object is chosen it will return a calculation of the
area of the shape.

In the following sample of a Java program, both lines look very similar and both objects
are being sent the same message.

areaOfShape1 = shape1.getArea();

areaOfShape2 = shape2.getArea();

However, the actual methods executed might be different, if shape1 is based on a


Circle class and shape2 on a Square class.

Extension Activity 4 – Area calculation for different shapes

Looking at out example for LibraryItem classes, it might be that the charge for late
returns is not simply an attribute set and stored for each individual object, but set
according to the sub-class of the object. So it might be that objects of subclass TextItem
always have a late return charge of 0.05 pounds per day, while objects of subclass
Recording have a late return charge of 50% of their weekly loan fee. In such a situation
sending an LibraryItem object the message getLateReturnCharge() would result in
polymorphism, since depending on which subclass the object was an instance of,
different methods would be executed for this same message.

Another example:

For example, to calculate the monthly pay for a lecturer, one might execute a method to
divide the annual salary by 12; however, for a 0.5 part time lecturer one would need to
further reduce the 12 of annual salary by half again (or an appropriate amount for a 0.1
or 0.75 part time lecturer). In both cases the classes would have an operation called
something like caclulateMonthlyPay(), but the actual methods implemented for the
Lecturer class, and the PartTimeLecturer subclass would be different.

An important advantage of polymorphism is that it is possible to design systems in such


a way that it becomes easy for adding to a system at a later date. For example:

 the addition of new classes (they just need to have the same protocol as other
classes, but can implement their methods differently)
 methods can be re-implemented more efficiently at a later date for special, with no
changes to the rest of the software system.

Polymorphism is made possible through the dynamic and late binding of methods to
objects when a program is executing (rather than at compile time).

Graphical user interface system communication: event messages

A particular type of message an object of a class can receive is that of an event. Events
are messages that are generated by user interface objects, such as the windows,
menus, mice, keyboards etc.

Examples of events include:

 window resized
 window minimised
 window closed
 mouse button pressed down
 mouse button released
 mouse cursor moved to new X, Y position on screen
 a key was pressed
 a window has been moved (so may need to be repainted by a program)
 a button was clicked
 a menu item was chosen
Those objects that play a role in processing input from the user not only have methods
for messages they expect to be sent by other object, but also have methods specially
for dealing with user interaction events.

Extension activity 5 – Explore events from input devices

Multiple inheritance

It is often possible to reason about a class as if it were a direct subclass of 2 or more


classes – for example a Lecturer class might be a subclass of Employee and a subclass
of Student (since a lecturer might be registered for some part time course, for example).
Some object-oriented modelling and programming approaches allow a class to have
multiple inheritance by allowing 2 or more direct superclasses for the same class. This
can lead to efficient and elegant class hierarchies. It can also lead to ambiguous
inheritance decisions and more complex design and programming.

One of the strengths of Java is that by only having simple class hierarchies, where each
class as only a single direct superclass, many potential problems of clashes where an
attribute or operation could be inherited from 2 or more superclasses are completely
avoided. Single inheritance languages do generally provide mechanisms to support
some of the advantages of multiple inheritance – such as the interface mechanism
provided by Java.

The advantages and disadvantages of multiple inheritance are still being debated,
however for this module, by choosing to focus on a single inheritance programming
language, such debates can be put on one side to simplify the process of learning
object technology and its implementation in Java.

Extension Activity 1 – Completing the table of terminology

Based on your understanding gained from working through this unit, complete the table
of terminology. You may also wish to refer to other sources of reference for object
technology terms.

Discussion of Extension Activity 1

Completing the table of terminology


Upon completion of the Unit 01 unit test you will be able to view a completed table of
terminology.

Modelling term Implementation term

class or type class

instance object

attribute variable

operation method

state set of variable values

behavior when methods are


executed

message message

event event

Extension Activity 2 – Notemaking from Deitel & Deitel

Using the module glossary and this unit, write a description (and definition) for each of
the following:

 a computer
 programming languages
 a computer program
 machine code

Read Chapter 1 of Deitel and Deitel, making notes on the above concepts in particular.

 Identify any differences in the level of description between your original notes and
those made from reading Deitel and Deitel (i.e. the degree of abstractness or
concreteness)

Discussion of Extension Activity 2


Notemaking from Deitel & Deitel

In this unit we have start with abstract views of computers and systems etc. and moved
into move concrete definitions. In fact the module as a whole works this way - units 03
to 10 investigate the concrete details of the Java programming language, while the
introduction and first two units provide an overview and higher level introduction of
important concepts.

You will find much of Deitel and Deitel presenting a concrete view of computers and
Java programming – this text has been chosen for its breadth and detailed level of
presentation.

You are strongly encouraged to use additional on-line and written sources to help you
achieve a broad grasp of both an abstract and concrete understanding of computer
programming and object technology concepts.

Extension Activity 3 – Compiling and running the SimpleMessagesapplication

In this exercise you will compile the 3 Java source files that are needed to run the
SimpleMessages application. You will then run the application.

(1) create a new, empty directory (folder) on your computer’s hard disk called
"Unit1Activity12".

(2) copy into this directory the following files from the SimpleMessages application
page:

MyShape.java
MyCircle.java
DrawShapes.java

(3) Compile these source files as follows with the "javac" Java compiler:

javac MyShape.java
javac MyCircle.java
javac DrawShapes.java

If you get any error messages after entering a "javac" command, look up the problem in
either the FAQ list or the "Debugging Java Programs" list.

(4) Examine the list of files in this directory (either by viewing a folder window, or the
command line "dir" command).

You should now have six files in your directory:


MyShape.java
MyCircle.java
DrawShapes.java
MyShape.class
MyCircle.class
DrawShapes.class

(5) Run the class containing the "main()" method you wish to execute – in this case you
need to run the "DrawShapes" compiled class file.

java DrawShapes

(6) The "SimpleMessages" application window should appear on screen as shown


below.

Extension Activity 4 – Area calculation for different shapes

Run the "CircleSquare" application. A window should open, presenting at the top,
buttons to choose either "circle1" or "square1", on the left a set of buttons to send
messages and on the right a drawing area showing a small, black circle, and below it a
small, black square. Your computer should look similar to the screen shot in the figure
below:
You can select which object messages will be sent to by clicking the radio button next to
the object name "circle1" or "sqaure1".

By clicking the appropriate message buttons perform the following tasks on the circle
object:

(1) make circle1 red

(2) make square1 blue

(3) make circle1 larger

(4) make square1 larger

(5) find out the radius of circle1

(6) find out the radius of square1

(7) find out the length of sides of square1

(8) find out the length of sides of square2

(9) find out the area of circle1

(10) find out the area of square1

Discussion of Extension Activity 4


Area calculation for different shapes

Both MyCircle and MySquare are subclasses of the class MyShape. They have many
common attributes and operations. For example both MyCircle and MySquare objects can
have their colour changed to blue or red by sending the same messages to either object
– as demonstrated in tasks (1) and (2). Likewise instances of both classes have
operations for making themselves larger and smaller – as demonstrated in tasks (3) and
(4).

Tasks (5) and (6) involve sending a getRadius() message to the two objects. A MyCircle
object, not surprisingly replies to such a message with the number that is the value of the
radius attribute of the object. Again, not surprisingly, sending the same getRadius()
message to the square1 object results in a reply which states that the message is not in
the protocol for MySquare objects – of course squares do not have radii.

Tasks (7) and (8) demonstrate the same point as (5) and (6), except that in this case it is
the circle1 object that is sent a message that is not a member of its protocol.

Tasks (9) and (10) illustrate a case where two different classes have an operation of the
same name – in this case the getArea() operation. What is important is that the way the
area of a circle is calculated is very different from the way the area of a square is
calculated. So although the circle1 and square1 objects receive the same message, the
way their operations are implemented is different. This is an example of polymorphism,
one of the strengths of object technologies.

A formula for calculating the area of a circle is:

area = 2 * p* radius

A formula for calculating the area of a square is:

area = (length of side)

In the two examples of Java code below, don’t worry about special words like public and
return etc. – concentrate on seeing how an operation can be implemented in different
ways, and also reflect on the similarities (and differences) of how we express formulas,
and how they are expressed in the Java programming language.

The implementation of the getArea operation for the class MyCircle is:

public float getArea()


{
return ( 2 * Math.PI * radius );
}

The implementation of the getArea operation for the class MySquare is:
public float getArea()
{
return ( sideLength * sideLength );
}

The important issue with polymorphism is that sending the same message to different
objects can result in different instructions being executed, and possibly also different
object behaviour.

Another example of polymorphism, which is less explicit in the CircleSquare application,


is how the instances of the MyCircle and MySquare classes respond differently to a paint
message. Each time you send a message to an object in the CircleSquare application,
the object is also sent a paint message, telling the object to redraw itself on screen.
Once again we have an example of polymorphism, since the way a circle is drawn on
screen is different to the way a square is drawn. For example, the implementation of the
paint operation of the MySquare class is defines as follows:

public void paint( Graphics g )


{
// set up values for corners of square //
int left = xPos;
int right = (xPos + sideLength);
int top = yPos;
int bottom = (yPos + sideLength);
// draw lines for each side //
g.drawLine( top, left, top, right );
g.drawLine( top, right, bottom, right );
g.drawLine( bottom, right, bottom, left );
g.drawLine( bottom, left, top, left );
}

Note that the attributes xPos and yPos represent a corner, not the centre, of a square.
Also note that most computer drawing systems have the X-axis as normal (leftmost is
X=0, rightmost is some larger x value), but have an inverted Y-axis. So the top of a graphic
area is where Y = 0, and as one moves down the screen the Y-value increases. Don’t
worry about this right now – such issues are examined in detail in a later unit on graphics,
the point is mentioned here to explain why the bottom calculation involves the side length
being added to the top value.

It would be inappropriate to attempt to draw a circle made up of straight lines, and so the
circle paint operation is defined differently.

Extension Activity 5 – Input device event messages

This activity explores event messages send from input devices to application objects.

Perform the following tasks

(1) start notepad via the Windows "Start" menu


(2) minimise the window

(3) maximise the window

(4) type 3 lines that each say "this is a test"

(5) move the cursor with the arrow keys to the end of the top line

(6) use the mouse to position the cursor (caret) to the beginning of the second line

(7) run the application "SimpleMessages" and make the circle smaller

(9) For each of the above actions, write down one or more events that you may have
caused to be sent to the "notepad.exe" program.

Discussion of Extension Activity 5

Input device event messages

(1) You have sent many mouse move messages, while moving the mouse pointer
across the screen to the "Start" menu. You then sent left mouse button depressed and
released messages, as you clicked on the "Start" menu. You then sent more mouse
move and button depress/release messages choosing sub-menus.

(2) You sent mouse move and button messages.

(3) Again you sent mouse move and button messages.

(4) You sent some key press and release messages.

(5) You sent some more (arrow) key press and release messages

(6) You sent mouse move and button messages.

(7) You send mouse messages to run the application, and mouse press messages.

These examples help to illustrate one strength of object technology since classes for
things like windows and menus etc. can be created to deal automatically with events such
as window sizing, keypresses and mouse clicks. These classes can then send move
abstract messages, such as menu item chosen and button pressed messages for
applications to deal with. It would be very hard work for each new program to have to
write instructions for dealing with every single, low level event message a program might
be sent.
End of Unit Review

Before proceeding to the next unit you should work through this set of review questions.
When you have completed the questions you will be able to obtain the answers for future
reference.

Your performance with these questions will not affect your grade for the module, but may
be monitored so that your tutor can be alerted if you are having difficulty.

Please contact your tutor if you feel you have not done as well as you expected.

Unit 01 Application program list

Unit 01 Applications

For each of the Unit 01 applications the following steps indicate how to execute, view
the source code, or save the source code as a file:

 To execute an application

 Install the snjrt20 program by double clicking the "snjrt20.exe" icon


 Shutdown and then restart your computer
 To run any of the Unit 1 application simply double click on the applications
icon (so to run "CircleSquare.exe" just double click this applications icon)

 To view the source files for an application

 Go to the specified source file code, and save it.

 To save the source code as a file

 Click on the source code file Hyper link


 A "Save As" widow will appear, So save it in a place on your hard disk.
Make sure that you know where you saved the file
 Go to the place where you saved the file and open the file by double
clicking it.

Activity "SimpleMessages"

Executable application:
SimpleMessages.exe

Source code listings:

MyCircle.java
MyShape.java
DrawShapes.java
DrawPanel.java

Activity "GetSetMessages"

Executable application:

GetSetMessages.exe

Source code listings:

MyCircle.java
MyShape.java
DrawShapes.java
DrawPanel.java
MySquare.java

Activity "TwoCircles"

Executable application:

TwoCircles.exe

Source code listings:

MyCircle.java
MyShape.java
DrawShapes.java
DrawPanel.java
TwoCircles.java

Activity "CircleSquare"

Executable application:
CircleSquare.exe

Source code listings:

MyCircle.java
MySquare.java
MyShape.java
DrawShapes.java
DrawPanel.java

Você também pode gostar