Object Oriented Programming 1
Engineering track / 2nd year
2024-2025
◼ 2. Objects and Classes
Azeddine Chikh
University of Tlemcen
General
0. Introduction to Java language
1. Basic principles
2. Objects and Classes
3. Messages and communication between objects
4. Encapsulation
5. Memory management of objects
6. Inheritance, Polymorphism and Abstract class
Objective
◼ This chapter aims to technically clarify the notion
of class. We will see that classes serve both as a
model to be strictly respected by objects, as well
as ideal modules for software organization.
◼ It is also a question of distinguishing the so-called
procedural approach, focused on the major
activities of the application, from the object
approach, focused on the actors of the simulation
and the way in which they interact.
Plan
◼ Constitution of an object class
◼ The class as a functional module
◼ Class as guarantor of its proper use
◼ The class as an operational module
◼ Object objective: the adventures of the OO
◼ Setting in practical
◼ Analysis
◼ Design
◼ Consequences of object
Constitution of an object class
An example of a class and the three types of information that compose it
Constitution of an object class
Object-oriented programming, or class-oriented programming?
◼ In reality, an OO programmer spends much more time doing classes than worrying about
what will happen to objects when they execute.
◼ Rather than “object-oriented programming”, it would have been more appropriate to
describe this type of programming as “class-oriented programming”!
The three information pieces of the class
◼ Any class definition includes three pieces of information:
◼ the name of the class
◼ its attributes and their types
◼ its methods.
Constitution of an object class
◼ Definition of a class method: with or without return
Comments
◼ /* … */ surrounds comments inside code. When comments remain on a single line, we can
also use //. Any commented writing is disabled in the code.
Functions and procedures
◼ Practitioners of procedural programming languages will find here the distinction generally
made in these languages between:
◼ a function (declared with return like any mathematical function f(x) in general) and
◼ a procedure (declared without return and which is limited to modifying data).
Method arguments
◼ The presence of arguments in the definition of a method serves to modulate the behavior
of the instruction body of this method. This is the equivalent of x in mathematical functions
f(x).
◼ In typed languages, the method arguments must be typed when it is declared. Thus, we
will declare void f(int x); so that this function only deals with integers, for example f(5).
Constitution of an object class
◼ Definition of a class method: with or without return
With return
int change() {
couleur = couleur + 1 ;
if couleur == 4 couleur = 1;
return couleur ; /* la méthode retourne un entier */
}
if (change() == 1) print ("le feu est vert")
int b = change() + 2 ;
Constitution of an object class
◼ Definition of a class method: with or without return
Without return
void clignote(int a) {
/* Affichage de texte à l’écran */
System.out.println("Une maniere de clignoter");
for(int i=0; i<2; i++) {
for (int j=0; j<a; j++) // on retrouve le “a” de l’argument
System.out.println("je suis éteint");
for (int j=0; j<a; j++)
System.out.println("je suis allumé");
}
}
Constitution of an object class
◼ Identification and overloading of methods by their
signature
Method overloading
◼ The overloading of a method aims to create a new one, whose signature differs from the
previous one only by the list or nature of the arguments.
Method signature
◼ The signature of the method is what allows it to be found in the method memory.
◼ It consists of the name, the list, as well as the type of the arguments.
◼ Any modification of this list could give rise to a new method, overloading the previous one.
Constitution of an object class
◼ Identification and overloading of methods by their
signature
Interface
◼ An interface consists only of a name and a set of method signatures, including the return
type associated with each signature.
◼ For example, the Vehicle interface could define the method void changeSpeed (int nv).
◼ An interface does not contain any implementation information for its signatures.
◼ If a class declares that it implements an interface, it is required to provide code for each of
the methods defined by the interface.
Constitution of an object class
◼ Identification and overloading of methods by their
signature
Interface
◼ Note that both interfaces and classes are two possible types.
◼ The type of a variable or attribute could be a primitive type, a class or an interface.
◼ In OO, it is preferable to type variables by interfaces rather than by classes.
◼ The compiler checks that variables typed by an interface only refer to objects that implement it.
◼ In addition, the compiler checks that only methods belonging to the interface are called on the
variables typed by the latter.
◼ In essence, the interfaces constitute the guide of all the objects from the classes which
implement this interface, which can inform any other class wishing to interact with them.
Plan
◼ Constitution of an object class
◼ The class as a functional module
◼ Class as guarantor of its proper use
◼ The class as an operational module
◼ Object objective: the adventures of the OO
◼ Setting in practical
◼ Analysis
◼ Design
◼ Consequences of object
The class as a functional module
◼ Differentiation of objects by the value of attributes
◼ The existence of the class will save us from specifying, for each object, the number and
type of its attributes, as well as the signature and the body of the methods which
manipulate the latter.
◼ This is a significant savings in writing and the effect of this increases with the number of
objects from the same class.
◼ These objects will be stored in specific computer sets, called collections. These may be
extensible sets (lists) or not (arrays).
◼ The only information that remains to be specified when creating an object is the initial
value of its attributes.
◼ This is the role of a particular method bearing the same name as the class: the
constructor.
The class as a functional module
◼ The constructor
◼ The constructor is a special method, having the same name as the class (in the most
popular OO languages) and which is defined without any return. Its mission is to initialize
the attributes of an object upon its creation.
◼ Unlike other methods which then execute on an already created object, the constructor is
only called when the object is constructed.
◼ A default version is always provided by programming languages. However, as soon as a
constructor is defined in the class, and as long as it receives one or more argument(s), it
will no longer be possible to create an object without indicating any argument value
(unless the constructor is explicitly overloaded by another that receives no arguments).
◼ The classic recommendation in programming is to avoid relying on the “default” and to
always provide a constructor for each of the classes created, even if it is limited to
reproducing the default behavior.
The class as a functional module
◼ The constructor
Addition of two overloaded constructors in the FeuDeSignalisation class
The class as a functional module
◼ The constructor
◼ FeuDeSignalisation class could be defined as follows:
FeuDeSignalisation(int positionInit, double hauteurInit) {
/* pas de retour pour le constructeur */
position = positionInit ;
hauteur = hauteurInit ;
couleur = 1 ;
}
The class as a functional module
◼ The constructor
◼ The instruction for any object creation should now be as follows:
FeuDeSignalisation unNouveauFeu = new FeuDeSignalisation (1, 3);
◼ This same instruction could be broken down into two parts as follows, first:
FeuDeSignalisation unNouveauFeu = null ;
◼ At the end of this first statement, only the referent is created and typed.
◼ The rest of the instruction, the creation itself, will only take place during execution.
unNouveauFeu = new FeuDeSignalisation (1, 3);
/* Création de l’objet et affectation de son adresse comme valeur du référent */
The class as a functional module
◼ The constructor
◼ Why is it necessary to indicate the name of the class twice in the previous instruction,
when typing the object (its declaration) and when calling the constructor.
◼ The reason is very simple. We should know that the class entered on the left could be
different from the class entered on the right.
◼ More precisely, the type of the object known only to the compiler could be a superclass
of the class referred to by the constructor (and which will only be revealed at runtime).
The object could be typed by an interface rather than by a class.
◼ We must accept at this stage that the compiler, although severe and powerful, does not
have complete knowledge of what will happen at runtime, starting with the definitive type
of objects, their ultimate class.
The class as a functional module
◼ The constructor
The three steps of constructing an object via “new”
The class as a functional module
◼ Static
◼ In the days of the earliest programming languages, all the memory space needed to
store data was reserved at the start of the program.
◼ At the end of the compilation, there was a way to predict how much RAM the program
would need. When executed, the program simply modified the values of the variables
stored in this memory.
◼ Then, the languages authorized the allocation of memory during the execution of the
code, but always under control and in a dedicated and particular memory space whose
management is carried out according to a principle called "stack memory", always
current in most languages today.
◼ This mode of memory management is also described as “static ”.
The class as a functional module
◼ Dynamic
◼ The small reserved word, new, authorizes a program, during its execution, not only to
allocate memory space for placing new variables there (here, this is reduced to only
objects), but also to place them anywhere in this memory.
◼ This alternative mode of memory management is generally described as “dynamic”.
Plan
◼ Constitution of an object class
◼ The class as a functional module
◼ Class as guarantor of its proper use
◼ The class as an operational module
◼ Object objective: the adventures of the OO
◼ Setting in practical
◼ Analysis
◼ Design
◼ Consequences of object
Class as guarantor of its proper use
◼ The fact that all object creation and manipulation is entirely dependent on what is
provided in its class gives many advantages to OOP.
◼ In Java, as the compiler's critical function is to produce “executable” code, it will take
care to verify that nothing written by the programmer can be a source of unforeseen
events or errors.
◼ And this is where the class again plays a considerable role, by allowing the compiler to
ensure that what is asked to objects (essentially the execution of messages) is within the
range of possibility.
◼ The class is like a contract passed to the compiler. It disappears during execution to give
place to the objects, while ensuring in advance that everything they do will conform to
what is specified in the contract. We cannot send a message to the object, that is not
one of the methods provided by its class.
Class as guarantor of its proper use
Statically typed and strongly typed language
◼ A programming language is said to be statically typed or even “strongly” typed when the
compiler verifies that we only do with the objects and variables of the program what is
authorized by their type.
◼ This verification has the effect of increasing the reliability of program execution. Java is
strongly typed and the compilation step is essential. This is not the case for Python and
PHP.
Plan
◼ Constitution of an object class
◼ The class as a functional module
◼ Class as guarantor of its proper use
◼ The class as an operational module
◼ Object objective: the adventures of the OO
◼ Setting in practical
◼ Analysis
◼ Design
◼ Consequences of object
The class as an operational module
◼ Class memory and object memory
◼ About the two characteristics of the class, we could very synthetically say of :
◼ the first that it is its passive part – represented by the attributes, which are
associated with the objects –, and of
◼ the second that it is its active part – represented by the methods, as associated
with the class, because the methods are common to all objects of the same class.
◼ We consciously forced this separation by installing attributes and methods in very
distinct memory spaces.
◼ For attributes whose value is common to all objects, it would be more natural and
certainly economical, like methods, to install them in memory spaces dedicated to
classes.
◼ We call this type of particular attributes, whose values are shared by all objects and
therefore become class attributes rather than object attributes, static attributes.
The class as an operational module
◼ Class and instance methods
Static
◼ Attributes of a class whose values are common to all objects and which thus become
directly associated with the class, as well as methods that can be executed directly from
the class, will be declared as static.
◼ They can be used in the absence of any object. A static method can only use static
attributes and can only call methods within it that are also declared as static.
The class as an operational module
◼ Class and development logistics
Natural and dynamic connection of classes
◼ The class, because it is like a small program, constitutes an ideal module for dividing the
software into its different files.
◼ The semantic link between classes, made possible if a class integrates into its code a
call to another, should be sufficient to dynamically link, during compilation and execution
of the code, the files in which these classes are written.
◼ It is mainly in Java that this logic of semantic organization of code according to its
classes, isomorphic to the physical organization into files, is most rigorously forced by
syntax. This is a very good point in favor of Java.
Plan
◼ Constitution of an object class
◼ The class as a functional module
◼ Class as guarantor of its proper use
◼ The class as an operational module
◼ Object objective: the adventures of the OO
◼ Setting in practical
◼ Analysis
◼ Design
◼ Consequences of object
Object objective: the adventures of the OO
◼ The major objective of OO is to facilitate the development of complex systems.
Managing complexity is the main difficulty in computer science.
◼ OO tackles this by dividing the program into entities that are as independent as possible.
If two pieces of the program are independent, a modification of one will not require
modifying the other accordingly.
◼ By associating methods in the class with the attributes they modify, the object is not
limited to simply storing its state, but above all it becomes the first responsible of these
changes.
◼ If any first object wishes to learn about the state of a second or to undertake to modify it,
it will have to go through the methods of the latter.
◼ The object must always be accompanied by its guide defined in a separate data
structure: its interface.
Object objective: the adventures of the OO
◼ Argumentation for the object
◼ Today, progress in software development seeks to make programming increasingly
distant from the intimate functioning of microprocessors, and closer to our spontaneous
way of solving problems.
◼ Simplicity of design, accessibility, adaptability, reliability and easy maintenance are the
paths to progress, much more than program optimization in calculation time and memory
space.
◼ The more complex the application to be created and involving multiple interacting actors,
the more beneficial it becomes to distance ouselves from the constraints imposed by the
processor, to make the world around us the main source of inspiration.
Object objective: the adventures of the OO
◼ Transition to object
◼ OO is at the crossroads of progress in software engineering, in programming and in
cognitive sciences.
◼ There are two ways of thinking about software development today :
◼ the so-called “procedural” way, represented by languages like C, Pascal, Fortran and Cobol,
◼ the so-called “object-oriented” way, represented by languages like C++, Java, Smalltalk, Eiffel,
C#, and Python. The second undoubtedly seems to surpass the first.
◼ There are many objective benefits of adopting OO practice in software application
development.
Plan
◼ Constitution of an object class
◼ The class as a functional module
◼ Class as guarantor of its proper use
◼ The class as an operational module
◼ Object objective: the adventures of the OO
◼ Setting in practical
◼ Analysis
◼ Design
◼ Consequences of object
Put into practice
◼ Simulation of an ecosystem
◼ A biologist wants to simulate a small ecosystem in which, as indicated in the following
figure, there are a predator (the lion), a prey (the bird) and resources (water and plant)
necessary for the survival of both animals.
Programming a small ecosystem
Put into practice
◼ Simulation of an ecosystem
◼ Let's briefly describe the scenario of this simulation. The prey moves towards the water,
towards the plant, or in order to escape the predator; it acts according to the first of
these objects that it spots.
◼ When the line of vision crosses an object, whatever it may be, the object is considered
spotted, vision no longer leaves the object and the animal moves towards the target or
flees from it.
◼ The predator moves towards the water or pursues the prey, again depending on the first
of the two objects perceived.
◼ The energy with which the two animals move decreases as they move and conditions
their speed of movement.
◼ As soon as the predator encounters the prey, it devoures it. As soon as the predator or
prey encounters water, it recharges its batteries (its energy increases) and the quantity
of water decreases (visually, the size of the water area decreases).
◼ As soon as the prey encounters the plant, it recharges its batteries (its energy also
increases) and the quantity of plant decreases (its size decreases). Finally, the plant
grows slowly over time, while the water area, on the contrary, evaporates.
Plan
◼ Constitution of an object class
◼ The class as a functional module
◼ Class as guarantor of its proper use
◼ The class as an operational module
◼ Object objective: the adventures of the OO
◼ Setting in practical
◼ Analysis
◼ Design
◼ Consequences of object
Analysis
◼ Procedural analysis
Procedural programming
◼ Procedural programming is carried out through collective access and global manipulation
of objects, in a few large functional modules which are mutually interdepending,
OOP
◼ OOP, on the other hand, is assigned to a large number of objects, successively passing
the relay to each other, for the execution of only the functions assigned
Analysis
◼ Main functions
The software breakdown of the procedural approach (with its large functional blocks)
Plan
◼ Constitution of an object class
◼ The class as a functional module
◼ Class as guarantor of its proper use
◼ The class as an operational module
◼ Object objective: the adventures of the OO
◼ Setting in practical
◼ Analysis
◼ Design
◼ Consequences of object
Design
◼ Procedural design
◼ In “procedural”, the major functions accomplished by the software, by nesting one within
the other, are the path to the evolution of the entire approach.
◼ This approach poses several problems. First, as each procedure must process the entire
data set, its individual complexity will be a direct function of the number of the different
objects in the simulated world.
◼ Then, if we later want to add a new type of prey, we will have to review the entire code to
find all the places to modify: the behavior of each object is dispersed throughout the
code.
◼ In addition, the fact of processing the entire world in a single block makes any prospect
of parallelizing the program very complicated.
◼ Finally, if the need emerged to change the data encoding, we practically have to rewrite
the entire program.
Design
◼ Object Design
◼ OO Design first seeks to identify the actors in the problem and transform them into
classes grouping together their structural and behavioral characteristics, then finally into
interfaces only keeping the behavioral part.
◼ The actors are not limited to existing structurally, they stand out above all by the
behavior adopted, by what they do, for themselves and for others.
◼ It is no longer the major functions that guide the modular construction of the software,
but the classes/actors themselves. The actors here are obvious: the prey, the predator,
the water and the plant.
◼ Once we have established the attributes of each, the big difference with the previous
approach will consist of carrying out a new functional analysis, but this time based on
each actor and their interactions.
◼ Instead of having a large data structure that we manipulate in one block, this time we will
divide the world into a set of objects.
Design
◼ Object Design
◼ By imagining that we discretize the flow of time in the simulation, we will ask each object
to evolve at each stage. All objects in the simulation must therefore be able to receive
the “evolve” message.
◼ Let's see how each type of object evolves. Let's start with the simplest: the plant grows
and the water evaporates. Animals are more complex, since they can move : they see
what is around them and act accordingly. Their method “evolves” will therefore have to
take into consideration all the other objects, hence the interactions. The animal itself
must be able to decide, for each other object in the world, whether it wants to flee it, get
closer to it or ignore it.
◼ Now let's move on to interactions. When an animal overtakes a resource, it can consume
it. In terms of interactions, the animal sends and the resource receives a “decrease”
message, with an argument indicating the quantity. The links between objects and
methods are shown in the figure.
Design
◼ Object Design
In the OO approach, the division of the software is done between classes which group together the structural
descriptions with the activities concerning them. Classes interact with each other.
Plan
◼ Constitution of an object class
◼ The class as a functional module
◼ Class as guarantor of its proper use
◼ The class as an operational module
◼ Object objective: the adventures of the OO
◼ Setting in practical
◼ Analysis
◼ Design
◼ Consequences of object
Consequences of object orientation
◼ The actors of the scenario
◼ The software division is carried out based on the major actors in the situation, and no
longer on the major activities specific to the situation. An obvious advantage is that the
first division appears much more natural to implement than the second.
◼ It is more intuitive to separate the program to be carried out into its four actors than into
its three major activities. We do not perceive the savannah as the meeting of three major
activities (migratory, evolutionary and food), but first as a set of animals and plants.
◼ Another significant advantage is that, in the procedural approach, all activities involve all
objects. This has the effect of increasing the difficulties of maintaining and updating the
software. Change anything in the description of an object and you risk having to rework
the entire code. On the contrary, in the OO approach, if we change the structural
description of water, it is only the Water class that will have to be re-examined.
Consequences of object orientation
◼ Developmental independency and functional dependency
Functional dependency versus software independency
◼ While the execution of an OO program is essentially based on a set of interactions
between dependent classes, everything is syntactically implemented during software
development to maintain a great deal of independency between classes.
◼ This independency during development promotes both the distribution of tasks between
programmers and the stability of codes during their maintenance, their reuse in different
contexts and their evolution.
◼ It is particularly accentuated by the interface mechanism, which makes it possible to
express directly in the code the minimum quantity of information that one class must
have about another. The less each class knows about the others, the more independent
they are in development.
Consequences of object orientation
◼ Developmental independency and functional dependency
◼ Thus, the dependency between two classes is realized directly between them, without
calling a more global software module grouping them within it.
◼ The predator will have to spot the prey, then catch it and finally devour it. It will do this by
activating a number of its methods, which, in turn, will require executing methods directly
on the prey.
◼ Similarly, when the prey drinks water, it will activate the Water class method, responsible
for its reduction in quantity.
◼ In essence, the dependencies between classes are thought two by two, and are not
submerged in software activity modules.
◼ This leads to a design of programming in the form of a set of client-provider (or server)
pairs, in which each class will be in turn client and provider of one or more others.
Consequences of object orientation
◼ Collaboration of classes two by two
◼ A set of objects acting in pairs and by sending messages favors the fragmentation of the
program by forcing the independency of the classes; two by two is always better than all
with all.
◼ The more decomposable the program is, the easier it will be to assign its modules to
different programmers and the fewer the consequences caused by changing one of its
modules will be.
Consequences of object orientation
OO compared to procedural in performance and calculation time
◼ Everything contributes to making OO programs large consumers of memory
(proliferation of objects, distributed anywhere in the memory, thus violating the principles
of computer “locality”) and of calculation time (finding in memory the objects and
methods at execution, then translate, at the last moment, the methods into their
executable form, not to mention the garbage collector and other performance
“breakers”).
◼ The only time and resources really saved are those of the programmers, both during
development and during maintenance and evolution of their code.
◼ OO simply considers that programmer time is more valuable and more expensive than
machine time.
References