Introducing To Object-Oriented Programming
Introducing To Object-Oriented Programming
Introducing To Object-Oriented Programming
Olexiy Tykhomyrov
Contents
1.1 Acknowledgements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 History notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
2 Introduction 3
2.1 Acknowledgements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.2 History notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.3 Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3 An Object-Oriented World 7
3.1 Encapsulation Example . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.2 Inheritance Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.3 Polymorphism Example . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.4 A Word of OOP Vocabulary . . . . . . . . . . . . . . . . . . . . . . . . . 8
5 Encapsulation 11
5.1 Instance and Class Variables . . . . . . . . . . . . . . . . . . . . . . . . 14
5.2 Instance and Class Methods . . . . . . . . . . . . . . . . . . . . . . . . 14
5.2.1 Sample Program . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
5.3 Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
5.4 Constructors, Destructors, and Garbage Collection . . . . . . . . . . . 19
6 Inheritance 21
6.1 Single and Multiple Inheritance . . . . . . . . . . . . . . . . . . . . . . 22
6.2 The ISA Relationship . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
7 Polymorphism 23
7.1 Overloading Methods as a Form of Polymorphism . . . . . . . . . . . 23
7.2 Overloading of Operators . . . . . . . . . . . . . . . . . . . . . . . . . . 23
7.3 Overriding Methods as a Form of Polymorphism . . . . . . . . . . . . 24
8 Exception Handling 25
8.1 Exception Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
8.2 Advantages of Using Exception Handling . . . . . . . . . . . . . . . . . 26
1.1 Acknowledgements
These notes were written as a compilation of ideas and examples from a variety of
authors, but Ulrich Raich was the very first enthusiast who did the notes about
J AVA for the Real-Time College in Dakar, and lots of ideas and examples were
taken from those notes. Catharinus Verkerk suggested lots of improvements and
ideas about planning the lessons. Lot of materials was stolen from the notes of
Prof. Richard Baldwin and Paul Ramos.
not feasible. “Spaghetti programming”, the path a program would take which
resembled a pot of spaghetti, was the result.
One of the super-programmers Donald Knuth estimated the mean quantity of
“GO TO” statements in F OR TRAN programs and obtained about 13%. So the en-
emy of all programmes was identified and banned. A new language was invented
similar to A LGOL1 in order to implement structured programming. P ASCAL, the
name of that new language, is still used for teaching and as a general purpose
programming language. Its newest version, D ELPHI, is so far from the P ASCAL,
that the other name for the language occurred.
The main distinguishing features (grown from A LGOL) are, each program was
subdivided into blocks with one entry and one exit: functions, procedures but
also if-then-else clauses, for, repeat-until and do-while loops. Functional entities
needed to be identified and the problems to solve were subdivided into func-
tions and procedures, where each subroutine implemented one of these func-
tional units. Each subroutine had a well defined interface, i.e. (parameters to
be passed of a given type) and it was even possible to have several programmers
working on the same project, each one implementing a few procedures, and then
stick them together to form a working program, which sometimes worked. To
run a program (written in F OR TRAN or P ASCAL) a translator was used to produce
machine-dependent code of a target computer, so the resulted binary code would
only run on the single type of machine and unfortunately incompatible between
compilers. To run the program on the other target machine at lease some adap-
tation and modification of the source code should have been done.
Computers became more and more powerful, and memory and disk space
became more cheaper, but software was still incredibly complex, huge and non-
portable. It was the new software crisis, and in addition Internet changed the
view of computing within a few years and most of todays computers are included
in some network or another. Writing programs for a single type of CPU became too
costly (now the cost lies on the software and not on the hardware side any more)
and we needed a language whose “binary code” could run on any machine, even
better: if it can be downloaded over the Internet and executed on any machine
without the user being aware of the download process. Just as P ASCAL was the
miracle language that could solve all problems and solve them forever, J AVA and
OOP is supposed to do the same for all future problems, so you recognise how
important OOP is.
In these notes we concentrate on Object-Oriented Programming (OOP). Notes
are intended to be independent of any specific language. As a practical matter, it
is necessary to use some language for illustration purposes, and rather than to
conjure up some artificial language, examples in this lesson are provided using
the J AVA language.
Some languages such as C do not readily support OOP. Other languages such
as C++ support OOP, but don’t require you to use the object-oriented features of
the language.
J AVA requires you to program by means of OOP techniques. In particular,
it is not possible to write even the simplest program in J AVA without taking an
object-oriented approach. You may do an excellent program, or you may do a
poor program, but your J AVA program must use objects.
1
A LGOL means Algorithmic Language
Although J AVA has some very complex and sophisticated features such as
multi-threading, it is not difficult to learn. To program in J AVA, you have to know
these two items:
The first of these challenges can be met on a gradual basis. In other words, it is
not necessary to know the entire class library to produce useful J AVA programs.
Learning new tools and J AVA abilities give you more to produce more powerful
programs.
The second challenge cannot be met on a gradual basis. It is not possible
to create even the simplest J AVA program without programming in the object-
oriented paradigm.
2 Introduction
2.1 Acknowledgements
These notes were written as a compilation of ideas and examples from a variety of
authors, but Ulrich Raich was the very first enthusiast who did the notes about
J AVA for the Real-Time College in Dakar, and lots of ideas and examples were
taken from those notes. Catharinus Verkerk suggested lots of improvements and
ideas about planning the lessons. Lot of materials was stolen from the notes of
Prof. Richard Baldwin and Paul Ramos.
of thought is talking about OOP and J AVA but. . . does anybody really know what
it all exactly means?
When first computers came into the market, computer hardware was terribly
expensive: a Digital minicomputer in the early seventies cost several hundred
thousands dollars but was extremely limited compare to a 1000 dollar PC you
can buy nowadays in any supermarket.
Since a computer cost much more than cost of labor, programming has been
done in a way to maximise use of the precious hardware resources and so the
programs were hardware oriented. Those days it was extremely important to fit
the code into the small amount of available core memory, where each bit was
hand wired. Disk space was around 5Mbyte and it had to keep also an operat-
ing system. A program should have used the central processor of the computer
very carefully, so each piece of code was written to minimise CPU time as well.
Naturally many programs were written in assembler, the most hardware oriented
language. For scientific computation F OR TRAN was used, the language designed
exactly for such kind of things: F OR TRAN means Formula Translation.
As computers became more elaborate. more powerful and hardware resources
got cheaper, the amount of software to be provided grew catastrophically and
soon exploded. The demand could not be fulfilled by the methods used in those
times and the first software crisis had appeared. People learned that writing
large programs without thinking of modularisation and structuring was simply
not feasible. “Spaghetti programming”, the path a program would take which
resembled a pot of spaghetti, was the result.
One of the super-programmers Donald Knuth estimated the mean quantity of
“GO TO” statements in F OR TRAN programs and obtained about 13%. So the en-
emy of all programmes was identified and banned. A new language was invented
similar to A LGOL2 in order to implement structured programming. P ASCAL, the
name of that new language, is still used for teaching and as a general purpose
programming language. Its newest version, D ELPHI, is so far from the P ASCAL,
that the other name for the language occurred.
The main distinguishing features (grown from A LGOL) are, each program was
subdivided into blocks with one entry and one exit: functions, procedures but
also if-then-else clauses, for, repeat-until and do-while loops. Functional entities
needed to be identified and the problems to solve were subdivided into func-
tions and procedures, where each subroutine implemented one of these func-
tional units. Each subroutine had a well defined interface, i.e. (parameters to
be passed of a given type) and it was even possible to have several programmers
working on the same project, each one implementing a few procedures, and then
stick them together to form a working program, which sometimes worked. To
run a program (written in F OR TRAN or P ASCAL) a translator was used to produce
machine-dependent code of a target computer, so the resulted binary code would
only run on the single type of machine and unfortunately incompatible between
compilers. To run the program on the other target machine at lease some adap-
tation and modification of the source code should have been done.
Computers became more and more powerful, and memory and disk space
became more cheaper, but software was still incredibly complex, huge and non-
portable. It was the new software crisis, and in addition Internet changed the
2
A LGOL means Algorithmic Language
view of computing within a few years and most of todays computers are included
in some network or another. Writing programs for a single type of CPU became too
costly (now the cost lies on the software and not on the hardware side any more)
and we needed a language whose “binary code” could run on any machine, even
better: if it can be downloaded over the Internet and executed on any machine
without the user being aware of the download process. Just as P ASCAL was the
miracle language that could solve all problems and solve them forever, J AVA and
OOP is supposed to do the same for all future problems, so you recognise how
important OOP is.
In these notes we concentrate on Object-Oriented Programming (OOP). Notes
are intended to be independent of any specific language. As a practical matter, it
is necessary to use some language for illustration purposes, and rather than to
conjure up some artificial language, examples in this lesson are provided using
the J AVA language.
Some languages such as C do not readily support OOP. Other languages such
as C++ support OOP, but don’t require you to use the object-oriented features of
the language.
J AVA requires you to program by means of OOP techniques. In particular,
it is not possible to write even the simplest program in J AVA without taking an
object-oriented approach. You may do an excellent program, or you may do a
poor program, but your J AVA program must use objects.
Although J AVA has some very complex and sophisticated features such as
multi-threading, it is not difficult to learn. To program in J AVA, you have to know
these two items:
The first of these challenges can be met on a gradual basis. In other words, it is
not necessary to know the entire class library to produce useful J AVA programs.
Learning new tools and J AVA abilities give you more to produce more powerful
programs.
The second challenge cannot be met on a gradual basis. It is not possible
to create even the simplest J AVA program without programming in the object-
oriented paradigm.
2.3 Preface
To solve a problem we usually think about it first generally, on abstraction level.
We try to calculate resources, (money, e.g): we decompose the problem. In case of
limitation the human may use some tricks: if we do not have enough wallpaper,
we may not cover some hidden places: furniture, pictures, etc. can help. It means
we try to organise the solution from the available resources according to a plan.
These three elements of solving any problem, abstraction, decomposition and
organisation together calls a paradigm. Previous programmers experience was
based on functional paradigm.
Imagine that we are going to reach Trieste by car so we start to think how to
do that. According to an old paradigm of programming we should have thought
of the problem in terms of functions acting on data :
On abstraction level: think of the problem in terms of a process that solves it,
i.e. how to drive a care, how to collect necessary things, etc.
On decomposition level: think how to break all this processing down into small
manageable processing units, or functions; e.g. how to move a car from one
point to another. We recognise driving in the town differs from driving in the
highway. We think how to do stopping/starting the car etc. So we create
functions;
On organisation level: set up our functions so they call each other according
to the rules. We set up sequences of function calls, passing different argu-
ments to the functions, etc.
.
So, an introductory description of OOP can be based on the following guide-
line:
The solution to the problem should resemble the problem, and observers
of the solution should be able to recognise the problem without necessar-
ily knowing about it in advance.
A good example of this guideline from the computing world is the use of OOP
to develop a stack class from which stack objects can be instantiated. If a stack
is implemented as a class, instantiated as an object, and documented appropri-
ately, programmers familiar with stacks, queues, and other similar data struc-
tures will recognise it as a stack without other prior knowledge.
3 An Object-Oriented World
In OOP paradigm, from the programmers point of view, an object-oriented lan-
guage must support three very important explicit characteristics. We use these
concepts extensively to model the real-world problems when we are trying to solve
with our object-oriented programs. These three concepts are:
• encapsulation,
• inheritance,
• polymorphism.
To make these words even more confusing, almost every item or action used in
the OOP vocabulary has evolved to be described by several different terms, often
depending on the author(s) who wrote the particular book your are happy to be
reading. For instance, we can cause an object to change its state by sending it a
message, invoking its methods, or calling its member functions.
...
int tired; // an instance of an int type
Person man; // an instance of abstract data type
// identified as Person
...}
As you know, or can surmise, the integer data type comes from types which
are intrinsic in the language and named primitive types.
It is supposed that the abstract data type named Person you have invented
and declared somewhere. From the language point of view, this is a new data
type.
4.2 Abstraction
Abstraction is the specification of an abstract data type and includes a specifi-
cation of the type’s data representation and behaviour. It shows, what kind of
data can be held in the new type of data, and all ways of manipulation of that
data. An abstract data type is not intrinsic to the language, so compiler knows
nothing about how to manipulate it until it is specified by the programmer in an
appropriate manner.
J AVA programmers define the data representation and the behaviour of a new
type (present the specification to the compiler) using the keyword class. It means,
the keyword class is used to convert the specification of a new type into something
that the compiler can understand and work with.
Once the new type is defined, one or more objects of that type can be put into
existing state, from abstraction to reality. In other words, object of such kind can
be instantiated.
Once instantiated, the object is said to have state and behaviour. The state
of an object is determined by the current values of its data (instance variables)
and the behaviour of an object is determined by its methods (member functions
or instance methods).
The most popular example is a button, as an element of a GUI. If a button is
viewed as an object, we can visualised its state and behaviour easily. It has a
number of different states like size, position, caption, etc. Each of these states
is determined by data stored in the instance variables of the button object at any
given point in time. The combination of one or more instance variables for the
particular state of the object named a property of the object.
Similarly, when you click it with a mouse, that usually causes some action
defined for the button.
Each individual button object has instance variables, the values of which de-
fine the state of the button at any given time, from one side, and has certain
fundamental behaviour to respond to a click etc to use with some action.
class Human {
// code of the class
...
}
The key word in the definition is class, and its name is Human.
The behaviour of the new type is defined by three instance methods. One can
be used to store a data in an object of the new type, it is named setPerson. The
other one is named getHumanInfo can be used to retrieve a stored data from the
object. The last one is named Work and implements the changing of the object
tired, that is the member of a class Human. The code is not shown, we shall see
it later.
The corresponding lines look like these:
5 Encapsulation
The first of the three major principles of an object-oriented program is encapsu-
lation. On an abstract level we think in terms of independent agents working
together. Then we encapsulate the representation of the data and behaviour into
a class, thereby defining its implementation and interface .
According to good object-oriented programming practice, an encapsulated de-
sign usually hides its implementation from the class user and reveals only its
interface. A seed of clemantite was created in such manner. Realisation of all
its behaviour are hidden from us, we know only how to grow it, we know the
interface.
God did not provide detail documentation on how seeds are implemented, but
from the experience of human beings we know their interface and have the class
documentation about it’s interface. In technique, an ordinary user does not usu-
ally need to know how the steering mechanism of a car is implemented, and do
not know implementation details. A designer of class should have documentation
about implementation to develop and possibly change the user-level documenta-
tion.
38 return
39 ("Ouff... working again...");
40 }
41 else
42 return
43 ("Sorry can’t work, being too exhausted.");
44 } // end method Work
45
46 String rest() {
47 if (tired < 1)
48 return
49 ("Not very tired, so going to a party.");
50 else {
51 tired --;
52 return
53 ("Sleeping, hhhharrarrrdrrhhhh...");
54 }
55 }
56 } // end class Human definition
57
58 // Driver program
59
60 class ex1 { // defining the controlling class
61 public static void main(String[] args) { // define main
62
63 Human obj = new Human ();
64 obj.setPerson(0, "Olexiy", "Ukrainian"); //store data
65 // Get info about Olexiy
66 System.out.println ( obj.getHumanInfo() );
67 } //end main
68 } //end ex1 class
In general, to be visible to a user, the class consists of the public methods.
In our program all methods as well as classes are public by default. The class
user stores, reads and modifies values by invoking those methods. In the pro-
gram above we used method setPerson to input information about me, and than
getHumanInfo to get information about me.
The program we are examining has no hidden the implementation. From the
OOP point of view, this is not a well-designed program, but it is too simple!
Note, in our program we used methods setPerson and getHumanInfo. There
is a special note about names of the methods started with set and get:
Methods whose names begin with set and get have a special meaning
in J AVA. In particular, the introspection capability of the J AVA Beans API
considers these names to represent design patterns for manipulating the
properties of an object.
An object-oriented design is not a good design by default. In an attempt to
produce good designs, there are some general agreements on certain design stan-
dards for classes. For instance, the data members (instance variables) are usually
private. The interface usually consists only of methods and includes few if any
data members. This is, of course, a way of hiding the implementation.
However, there is one exception to this general rule: the data members which
are going to be used as symbolic constants are made public and defined to disal-
low modifying their values.
The methods in the interface should control access to, or provide a pathway
to, the private instance variables. The interface should be generic as possible,
in that it is not bound to any particular implementation. It means, from the
practical point of view, that the arguments of the method should have the same
meaning. If for some reasons changing implementation is needed, it should be
done in a such way to avoid changing the interface.
In our program we have only instance variables and instance methods. Let us
have a look at class variables and class methods.
1. Instance methods;
2. Class methods.
Knowing the situation with instance and class variables, you can guess easily:
methods designated static are class methods, and non-static are instance ones.
An instance method can only be invoked with an object of the class, so it is
bound to an object. If we invoke an instance method on a particular object, the
method will access the instance variables belonging to the object on which it was
invoked. It is very important to know, that the methods of a class have direct
access to the member variables of the same class, paying no attention to their
control access like public, private, protected.
Class methods can only access other class members (class variables or other
class methods). They cannot access instance variables or instance methods.
The most important thing about class methods is that they can be accessed
using the name of the class without a requirement to instantiate an object of the
class. As with class variables, class methods can be accessed by joining the name
of the class to the name of the method using the appropriate joining operator.
---------------
This cat has child(ren): 100
This cat has legs: 4
---------------
This cat has child(ren): 1220
This cat has legs: 4
Before we take a look at the listing of the program, lets examine some of the
interesting code fragments that make up the program.
The first interesting code fragment shows the declaration of two member vari-
ables of the class. One is a class variable named child and the other is an
instance variable named legs.
The body of the method is then enclosed within a matching pair of curly braces
{ }.
Now you can guess easily: the important thing to note is the use of the static
keyword in the definition of the class method.
The next code fragment is a single statement taken from the body of one of the
methods. This statement causes output to be displayed on the standard output
device.
This single statement incorporates classes, class variables, instance methods,
and overloaded operators, and illustrates some of the syntactical complexity in
an object-oriented program.
In J AVA, as in C, literal strings are enclosed in quotation marks. The plus sign
is overloaded in J AVA in this way to being used as an arithmetic addition operator,
and also to concatenate strings. Even more, the behaviour of the overloaded plus
operator also includes the ability to coerce its right operand into a string repre-
sentation if it isn’t already a string. In this case, the right operand is not a string,
but rather is the instance variable named instanceVariable. Thus the behaviour
of the overloaded plus operator is to first convert the value of instanceVariable
to a string representation and then to concatenate it to the left operand.
Now let’s take another look at the same two methods as before, this time
preserving the bodies of the methods for further examination.
// instance method
void instanceMethod ( ) {
Equally important is the fact that the class variable and the class method
can be accessed without the requirement to use an object of the class. The two
statements in the following code fragment simply use the name of the class to
access the class variable and the class method of the class.
Class variables and class methods can be accessed either via an object of the
class, or via the name of the class alone. Note, we do not put another value for
class variable “leg”: this value is shared between two object of the class cat: meow
and mour.
Finally, we put it all together in the J AVA application.
5.3 Messages
Methods are sometimes called member functions.
A message is simply the invocation of a method or member function.
The program sends a message to an object telling it to invoke the method and
sometimes provides parameters for the method to use.
Someone recently wrote that an object-oriented program consists simply of a
bunch of objects laying around sending messages to one another. This might be
a slight exaggeration, but is not too far from the truth.
...
String name;
// Parameterised constructor
cat (String n) {
name=n;}
...
System.out.println("This cat named " +
name +
" has child(ren): "
+ child);
...
cat mour = new cat("Pirat");
...
Garbage Collection The garbage collector is a part of the runtime system that
runs in a low-priority thread reclaiming memory that is no longer needed
by objects used by the program. An object becomes eligible for garbage
collection in J AVA when there are no longer any reference variables that
reference the object.
6 Inheritance
The first major characteristic of an object-oriented program is encapsulation.
The second one is inheritance. Let’s now have a look at it.
Having bought an old house to live, the person may try to reconstruct it in
order to have it extended into another one, more modern and more comfortable
without ruining the old version in general. Thus after reconstruction the house
will be a subclass the house that already existed. The new house inherits from
the existing one.
The same with the OO program: a class can normally inherit the attributes
and characteristics of another class. This mechanism can be blocked by using
different ways, though.
The original class is often called the base class or the superclass, and the new
class is often called the derived class or the subclass. Inheritance is often referred
to as extending the base class or superclass.
Inheritance is hierarchical. In other words, a class may be the subclass of one
class and the superclass of another class.
The derived class inherits the data representation and behaviour of the base
class except where the derived class modifies the behaviour by overriding meth-
ods. The derived class can also add new data representation and behaviour that
is unique to its own purpose.
A program can usually instantiate objects of a base class as well as of a class
which is derived from the base class. It is also possible to block instantiation of
the base class in some cases by defining it as an abstract base class. If the base
class is an abstract base class — one that exists only to be derived from – the
program may not instantiate objects of the base class but can instantiate objects
of classes derived from the base class.
The J AVA inheritance mechanism allows to build an orderly hierarchy of classes.
When several of your abstract data types have characteristics in common,
you can design their commonalities into a single base class and separate their
unique characteristics into unique derived classes. This is one of the purposes of
inheritance.
Remember, we have created a class Human, but not all humans are the same,
but different: we have different race, sex, culture, religion etc. Nonetheless we
have some very common features: two legs, two arms, one head. We all can
work, sleep, etc. Developed class Human has methods to indicate a human state
concerning possibility of working. This is the common parameter therefore of the
Human class we have built.
From this base class, we may derive a Gentleman class and a Lady class.
They certainly have different rest: the Lady prefers to drink tea with her neigh-
bours but the Gentleman largely his pint of beer in his favourite pub.
Objects of the classes will then be able to deal with all Human parameters as
well as new ones.
You may have noticed that in this hierarchical class structure, inheritance
causes the structure to grow in a direction from most general to less general.
This is typical.
Here you are an example. In the next fragment of the code one line of the code
is essential: it describes the Lady and Gentleman subclasses:
The keyword extends shows the Lady and Gentleman classes are subclasses
of the Human class.
Now we might have a look at the next fragment of the code, that was replaced
....
// a new method
public void drinking(){
System.out.println
("Drinking tea with my neighbors");
}
The last fragment of the code shows how to use new classes. Nothing new,
isn’t it?
...
Gentleman me = new Gentleman();
Lady anne = new Lady();
me.setPerson (0, "Olexiy", "Ukrainian"); //store data
you.setPerson(0, "Anne", "Russian"); //store data
System.out.println( me.getHumanInfo() );
System.out.println( you.getHumanInfo() );
...
has advantages in some cases, but can lead to difficulties in other cases. J AVA
does not support multiple inheritance but provides a special mechanism called
an interface to provide the same result. It is mentioned simply to inform you that
OOP language may, or may not provide mechanisms to achieve the same end
result.
7 Polymorphism
The last required characteristic of an object-oriented language is polymorphism.
The word polymorphism is Greek by origin. It means something like “one
thing, many forms”. In OOP polymorphism represents the idea of “one interface,
multiple methods” and means that functions or operators not implicitly recog-
nised by the compiler. J AVA does not support operator overloading, but does
support the overloading and overriding of methods.
• abs()
• labs()
• fabs()
C++ provides the opportunity, and (with one or two exceptions) the responsi-
bility for the programmer to define the behaviour of almost any operator that may
be applied to an object of a new class.
J AVA does not support operator overloading although in many cases over-
loaded operators will provide a much cleaner and more intuitive syntax.
12 class ex4 {
13 public static void main(String args[]) {
14 // Human class ref to Human class object
15 Human obj = new Human();
16 // Gentleman class ref to Gentleman class object
17 Gentleman me = new Gentleman();
18 // set information about me:
19 me.setPerson (0, "Olexiy", "Ukrainian");
20
21 // Display informatio about obj:
22 System.out.println( obj.getHumanInfo() );
23 // invoke method named drinking:
24 obj.drinking();
25
26 // Display information about me:
27 System.out.println ( me.getHumanInfo() );
28 // invoke method named drinking:
29 me.drinking();
30
31 // Human class ref to Gentleman class object
32 obj = me;
33
34 // Display information about obj:
35 System.out.println (obj.getHumanInfo() );
36 // invoke method named drinking:
37 obj.drinking();
38 }
39 }
Inheritance and method overriding are used in almost all J AVA programming.
Even the well-known “Hello World” J AVA applet requires that the Applet class be
extended and the paint() method be overridden.
8 Exception Handling
Although exception handling may not be considered as an OOP principle, J AVA
operates and requires it. Therefore, it is useful to speak about it a little in a
general sense.
We will attempt to look at the following topics briefly:
• What is an exception?
• How do we throw and catch exceptions?
• What do we do with an exception once we have caught it?
• How do we make use of the exception class hierarchy provided by the devel-
opment environment?
• Will we have advantages with exception handling?
Error indicates that a non-recoverable error has occurred that should not be
caught. Errors usually cause the J AVA interpreter to display a message and
exit.
Exception indicates an abnormal condition that must be properly handled to
prevent program termination.
Of all possible exceptions that J AVA can throw automatically, there is a subset
for which catching and processing is optional. The compiler allows you to ignore
the exceptions of this subset. If an actually ignoring exception occurs, it will be
caught by the runtime system, and the program will be terminated.
The remaining exceptions, that can automatically be thrown in Java, must be
recognised by program’s code in order to compile your program.
Recognised means the program’s code catch and either process the exception
object using another piece of the code, or your code can pass it up to the next
level in the method-invocation hierarchy for handling there.
J AVA program can then optionally execute a block of code designated by finally
which is normally used to perform some type of cleanup which is needed whether
or not an exception occurs.
If a method passes an exception up to the next level in the invocation hier-
archy, this must be declared along with the method signature using the throws
keyword.
If your code catches and processes an exception, the processing code can be
as elaborate, or as simple as you want to make it. The fact is, simply ignoring it
after you catch it will satisfy the compiler. This may, or may not be a good idea,
depending on the type of the exception.
All exception objects inherit the methods of the Throwable J AVA class.
separating Error Handling Code from “regular” one provides a way to separate
the details of what to do when something out-of-the-ordinary happens from
the normal logical flow of the program code;
propagating Errors Up the Call Stack lets the corrective action to be taken at a
higher level. This allows the corrective action to be taken in the method that
calling that one where an error occurs;
grouping Error Types and Error Differentiation allows to create similar hier-
archical structure for exception handling so groups they in logical way.
A test program should instantiate a Counter object and exercise the Counter by
incrementing it 4 times and displaying the result.
The output from the test program should be:
00
01
10
11
1
2 /* Counter designing */
3
4 class Bit{
5 int value;
6 void set(){//method to set the value of the bit to 0
7 value = 0;
8 }//end set()
9
10 int get(){//method to get the value stored in the bit
11 return value;
12 }//end get()
13
14 //method to implement binary addition
15 // we provide the table here:
16 int add(int inValue){
17 int carry = 0;
18 if((value == 0) && (inValue == 0)){ //0+0=0,c=0
19 carry = 0;
20 }else if((value == 0) && (inValue == 1)){//0+1=1,c=0
21 value = 1;
22 carry = 0;
23 }else if((value == 1) && (inValue == 0)){//1+0=1,c=0
24 carry = 0;
25 }else if((value == 1) && (inValue == 1)){//1+1=0,c=1
26 value = 0;
27 carry = 1;
28 }//end if statement
29
30 return carry;
31 }//end add()
32 }//end class Bit
33
34 class Counter{
35 Bit fstbit = new Bit();//instantiate three bit objects
36 Bit scndbit= new Bit();
37
38 //method to initialize the bit objects to 0
39 void initialize(){
40 fstbit.set();
41 scndbit.set();
42 }//end initialize()
43
44 //method to add 1 to lsb and have it ripple up
45 // through all three bits of the counter
46 void increment(){
47 scndbit.add(fstbit.add(1));
48 }//end increment()
49
50 //method to display the value of each bit in the counter
51 void show(){
52 System.out.println("" + scndbit.get() + fstbit.get() );
53 }//end show()
54
55 }//end class Counter
56
57 //controlling class required by Java application
58 class ex5 {
59 public static void main(String[] args){
60 //instantiate a counter object
61 Counter myCounter = new Counter();
62 myCounter.initialize();//initialize the counter object
63 myCounter.show(); //display contents of counter object
64 //increment and display counter object
65 for(int cnt = 0; cnt < 3; cnt++){
66 myCounter.increment();//increment it
67 myCounter.show();//display it
68 }//end for loop
69 }//end main()
70
71 }
72
The program includes a class named Bit with a data member named value
as well as methods to set the instance variable, get the instance variable, and
add a 1 to the value of the instance variable returning the carry from the binary
addition. These items you can find as nouns or verbs in the description.
Also as you can see, the design resulted in a class named Counter which had
three embedded Bit objects as instance variables or data members. This class
has a method named initialise that is used to initialise the two-bit counter to 00.
This class also has a method named increment which adds one to the least-
significant bit, adds the carry from the least significant bit to the middle bit, and
adds the carry from the middle bit to the most-significant bit. This is the typical
ripple pattern for a binary counter.
This class also has a show method that displays the values stored in each of
the two Bit objects in the order from most-significant to least-significant.
This program also contains a class named ex5 which is not represented by a
noun in the narrative description. This is because all applications in J AVA require
a controlling class, and in this case the controlling class is named ex5.