OOPD
OOPD
Olexiy TYKHOMYROV
Department of Experimental Physics
Dnepropetrovsk Experimental Physics
Proulok Naukovij, 13
49050 GSP 50 Dnepropetrovsk
UKRAINE
________________________________________________________________
These lecture notes are intended only for distribution to participants
Object Oriented Programming Principles
Olexiy Ye. Tykhomyrov∗
LNS
∗
[email protected]
Contents
1 Introduction 1
1.1 Acknowledgements . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Historical Development . . . . . . . . . . . . . . . . . . . . . 1
1.3 Functional and OOP Paradigms . . . . . . . . . . . . . . . . 3
2 An Object-Oriented World 4
2.1 Polymorphism Example . . . . . . . . . . . . . . . . . . . . . 5
2.2 Inheritance Example . . . . . . . . . . . . . . . . . . . . . . . 5
2.3 Encapsulation Example . . . . . . . . . . . . . . . . . . . . . 6
2.4 A Word on OOP Vocabulary . . . . . . . . . . . . . . . . . . . 6
4 Encapsulation 9
4.1 Instance and Class Variables . . . . . . . . . . . . . . . . . . 12
4.2 Instance and Class Methods . . . . . . . . . . . . . . . . . . 12
4.2.1 Sample Program . . . . . . . . . . . . . . . . . . . . 13
4.3 Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
4.4 Constructors, Destructors, and Garbage Collection . . . . . 18
5 Inheritance 19
5.1 Single and Multiple Inheritance . . . . . . . . . . . . . . . . . 21
5.2 The is-a Relationship . . . . . . . . . . . . . . . . . . . . . . . 21
6 Polymorphism 22
6.1 Overloading Methods as a Form of Polymorphism . . . . . . 22
6.2 Overloading of Operators . . . . . . . . . . . . . . . . . . . . 22
6.3 Overriding Methods as a Form of Polymorphism . . . . . . . 22
7 Exception Handling 24
7.1 Exception Hierarchy . . . . . . . . . . . . . . . . . . . . . . . 24
7.2 Advantages of Using Exception Handling . . . . . . . . . . . 25
References 31
1
1 Introduction
1.1 Acknowledgements
The material covered in this Chapter was written as a compilation of ideas and
examples from a variety of authors, but Ulrich Raich was the very first enthu-
siast in our group who prepared the notes on Java for the Real-Time College in
Dakar in 1998. Lots of ideas and examples were taken from those notes in the
preparation of this Chapter. Catharinus Verkerk suggested lots of improvements
and ideas about planning the lessons. Lot of material from the notes of Prof
Richard Baldwin[6] and Paul Ramos[7] was used as well.
As computers became more elaborate and more powerful, and hardware re-
sources got cheaper, the amount of software to be provided grew catastrophically
and soon exploded. The demand for new software could not be fulfilled by em-
ploying the methods used at the time and the first software crisis 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 to be around 13%. So the en-
emy of all programs was identified and banned. A new language was invented
similar to A LGOL1 in order to implement structured programming concepts. This
new language called P ASCAL is still used as an excellent language for teaching,
and to a lesser extent as a general purpose programming language. Following
the modern trend in object orientation P ASCAL was extended to become a new
language called O BJECT P ASCAL. Using O BJECT P ASCAL as the underlying lan-
guage a powerful development environment known as D ELPHI, used primarily to
build client/server applications for Microsoft Windows platform, was produced
by Borland.
The main distinguishing feature (grown from A LGOL) is that, each program
was subdivided into blocks with one entry and one exit. This was true not only
for functions and procedures but also for 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 functions and procedures, where each subroutine
implemented one of these functional units. Each subroutine had a well defined
interface, i.e. (parameters of a given type to be passed) and it was even possible to
have several programmers working on the same project, each one implementing
a few procedures, and then sticking them together to form a working program,
which most of the time 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.
The resulting binary code would only run on the single type of machine and
unfortunately was incompatible between computers. To run this program on
any other target machine at lease some adaptation and modification of the source
code was needed to be carried out.
Computers became more and more powerful, and memory and disk space be-
came cheaper, but software was still incredibly complex, huge and non-portable.
It was the new software crisis. In addition the Internet changed the view of
computing within a short period 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 in 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, Java and
OOP are supposed to do the same for all future problems; so you recognise how
1
A LGOL stands for Algorithmic Language
3
1. Learn how to productively utilise the large set of class libraries containing
dozens of classes and hundreds of methods which are provided as part of
the Java Development Kit1 or Java Standard (Enterprise) Edition to supple-
ment the language;
2. Learn how to design and program in the object-oriented paradigm.
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 Java pro-
grams. Learning new tools and Java capabilities certainly help you to produce
more powerful programs.
However the second challenge cannot be met on a gradual basis. It is not
possible to create even the simplest Java program without programming in the
object-oriented paradigm.
the problem in terms of functions acting on data . However in the OOP paradigm,
we think of the problem at three levels as follows:
On abstraction level - think of the problem in terms of a process that solves it,
i.e. how to drive a car, how to collect necessary things, etc.
On decomposition level - think of 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 on 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.
2 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:
• polymorphism,
• inheritance,
• encapsulation.
The solution to the problem should resemble the problem, and observers
of the solution should be able to recognise the problem without neces-
sarily 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.
Creating new improved objects using new definitions that extend existing
definitions is very common practice. This is one of the mottos of OOP, that
encourages the reuse of existing elements of programs.
3.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.
Java 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).
A 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
define 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
...
}
9
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:
4 Encapsulation
The first of the three major principles of an object-oriented program is encap-
sulation. 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 clemantine 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
10 Object Oriented Programming Principles
1 class Human {
2
3 int tired; // instance variables
4 String name; // of the class
5 String origin; //
6
7 // instance method to store data
8 void setPerson (int state, String na, String orig) {
9 tired = state;
10 name = na;
11 origin = orig;
12 } // end method setPerson
13
14 // instance method to display info of a human
15 String getHumanInfo() {
16 String info;
17 info = ("My name is " +
18 name + " and I am " +
19 origin + " ");
20 if (tired > 1)
21 info = info +
22 ("I am very tired.");
23 else
24 info = info +
25 ("and I am ready to work.");
26 return info;
27 } // end method showHumanInfo
28
29 void drinking(){
30 System.out.println(
11
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 Java. In particular, the introspection capability of the Java 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
standards 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 dis-
allow 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.
Class variables are shared among all objects of the class. They are very
similar to global variables. Only one copy of a class variable exists in
memory and all objects of the class can access them.
A very important characteristic of class variables is, that they can also be
accessed even if no object of the type was instantiated. You can access them
with dot operator, joining class name and the variable.
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.
// instance method
void instanceMethod ( ) {
System.out.println("This cat has child(ren): "
+ child);
} // end instanceMethod
static void classMethod ( ) {
System.out.println("This cat has legs: "
+ legs);
} // end classMethod
Here we see the code in the body of the methods accessing the member vari-
ables of the class. Recall that one of the member variables is an instance variable
named child and the other member variable is a class variable named legs.
The instance method named child is able to access and display both the
instance variable and the class variable while the class method named class-
Method is only allowed to access and display the class variable. Class methods
cannot access instance variables.
Now consider the contents of the main method as shown below. Java appli-
cations (but not applets) require a main method or function as the controlling
method of the application. In our simple application, we will use code in the ex2
method to instantiate an object and to access both the instance method and the
class method.
Recall that in order to access an instance method, it is necessary to access
it via an object of the class. The next code fragment is the code in the main
method, that instantiates an object named mour of the class named cat.
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 Java application.
4.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
18 Object Oriented Programming Principles
bunch of objects laying around sending messages to one another. This might be
a slight exaggeration, but is not too far from the truth.
Failure to deal with this important issue results in a condition often referred
to as ”memory leakage.”
...
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 Java when there are no longer any reference variables that
reference the object.
5 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.
20 Object Oriented Programming Principles
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 Java 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(){
21
System.out.println
("Drinking tea with my neighbors");
}
In this part of the program we declared a new method, drinking. Of course,
the very similar method the Gentleman has, but about beer!
Yet another sensitive fragment of the code shows manipulating with method
declared in the base class, Human. The keyword super is used to access that
method following by period, or dot operator.
// changing mathod getHumanInfo
public String getHumanInfo() {
String info;
info=super.getHumanInfo();
info=info+"and I am a lady.";
return info;
}
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() );
...
6 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. Java does not support operator overloading, but does
support the overloading and overriding of methods.
• abs()
• labs()
• fabs()
usually to meet the special requirements of the derived class, we say about run-
time polymorphism.
Java supports the notion of overriding a method in a base class to cause it
to behave differently relative to objects of the derived class. In other words, a
method named drinking() that is defined in the base class and is overridden in
the derived class would behave differently depending on whether it is invoked by
an object of the base class or by an object of the derived class.
In Java reference variable of a base-class type can be used to reference an
object of any class derived from that base class.
If an overridden method is invoked using that reference variable, the system
will be able to determine, at runtime, which version of the method to use based
on the true type of the object, and not on the type reference variable used to
invoke the method. This fact is illustrated in the following Java program.
The first, an overridden method named drinking() as a base-class reference
to a base-class object is invoked, then, as the second, the overridden method
named drinking() is invoked on a derived-class reference to a derived-class ob-
ject.
In the first case, the base-class version of drinking() is actually invoked. In
the second case, the derived-class version of drinking() is invoked. This is trivial.
Then as the third, is invoked the overridden method named drinking() on a
base-class reference which refers to a derived-class object. When this is done, it is
the version of the method defined in the derived class and not the version defined
in the base class that is actually invoked. This is the essence of runtime
polymorphism.
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 Java programming.
Even the well-known “Hello World” Java applet requires that the Applet class be
extended and the paint() method be overridden.
7 Exception Handling
Although exception handling may not be considered as an OOP principle, Java
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 de-
velopment environment?
• Will we have advantages with exception handling?
grouping Error Types and Error Differentiation allows to create similar hier-
archical structure for exception handling so groups they in logical way.
across the network and the tools to make them work together. The tools, classes,
etc. are included within the Java virtual machine.
CORBA, on the other hand, is a specification and an architecture for the
integration of networked objects. CORBA ensures interoperability of these dis-
tributed objects. Different vendors follow the CORBA specification to provide
tools, libraries, etc., for multiple languages and platforms. CORBA implementa-
tion for Java is provided by Sun Microsystems.
Design a digital Counter which has two bits with the following abilities:
1 + 1 = 0, c = 1
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 /* Counter designing */
2
3 class Bit{
4 int value;
5 void set(){//method to set the value of the bit to 0
6 value = 0;
7 }//end set()
8
9 int get(){//method to get the value stored in the bit
10 return value;
11 }//end get()
12
13 //method to implement binary addition
14 // we provide the table here:
15 int add(int inValue){
16 int carry = 0;
17 if((value == 0) && (inValue == 0)){ //0+0=0,c=0
18 carry = 0;
19 }else if((value == 0) && (inValue == 1)){//0+1=1,c=0
20 value = 1;
21 carry = 0;
22 }else if((value == 1) && (inValue == 0)){//1+0=1,c=0
23 carry = 0;
24 }else if((value == 1) && (inValue == 1)){//1+1=0,c=1
25 value = 0;
26 carry = 1;
27 }//end if statement
28
29 return carry;
30 }//end add()
31 }//end class Bit
32
33 class Counter{
29
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 Java
require a controlling class, and in this case the controlling class is named ex5.
References
[1] Bruno R. Preiss (2000). Data Structures and Algorithms with Object-Oriented
Design Patterns in Java.ISBN: 0-471-34613-6, University of Waterloo
[2] Peter Coad & Edward Yourdan Object Oriented Design (Yourdon Press Com-
puting Series) (1991).
[3] Mary Campione, Kathy Walrath. The Java Tutorial: Object-Oriented Program-
ming for the Internet (2nd Edition)
[4] The Java tutorial. A practical guide for programmers. Sun Microsystems.
Available online at http://java.sun.com
[5] The Java tutorial. A practical guide for programmers. Borland USA. Available
online at http://www.borland.com/delphi/