Object-oriented programming
Computer Science License 2 --- Sheet No. 1
First steps
It is recommended in Java that each class be defined in a
file that is its own. The name of the file must be the name of the class it
contains, to which the suffix is [Link] names must be
made up of concatenated words with the first letter capitalized.
Exercise no. 1 (Hello Groland!)
Write a Java program that displaysHello Groland!Compile and run this
program
Exercise No. 2
In Java, strings are represented by objects of the
classStringwhose instances are immutable. We want to be able to convert
strings containing numbers as integer values. Do it in
using the static methodstatic int parseInt(String)from the classInteger.
Define a string containing an integer and get its value in the form
of wholeintPay attention to the fact that the methodparseIntcan raise
the exceptionNumberFormatExceptionDeclare a string containing a
real number and obtain its value in the form of a floatdouble).
Exercise No. 3 (Tables)
• Declare two arrayst1andt2of integers.
• Create fort1andt2arrays of 5 integers.
• Initializert2with the values1, 567, -23, 78and4.
• How to declare, create, and initialize a
tableaut3in a single instruction?
• Write a static method to find the smallest element of a
table
• Write a static method to sort the elements of an array.
Exercise No. 4
Write a program that takes an expression from the command line
mathematics in prefix notation, of the form operator number number and which
evaluates it.
Exercise No. 5
Write a program that takes a list of integers from the command line, the
Copy into an integer array, sort the array, and finally display the content.
of the table.
Exercise No. 6 (References and Equalities)
• Createa tablet of 4 references on strings. Create a
string whose content isGoodAssign the first 2
elements of the table with this string and the third with the
chainHello. Create a new string whose content
is againGoodand assign this string to the last element of the
tabletCompare the elements of the tables two by two using the
[Link](), [Link]()and the operator==What
Do we observe?
• Concatenatet[0]with the chaindayusing the
[Link]()or the operator+Compare the elements 2 by 2
tables using the [Link](), [Link](), and
the operator==What do we observe?
Exercise No. 7
• Write a classPointrepresenting a point in the plane and having a
builderPoint(int, int), a method performing a translation, and
a method for signature comparisonboolean sameAs(Point).
• Create a point and designate it by two referencesp1andp2.
Comparep1andp2with the operator==and with the methodsameAsPerform
a translation ofp1and redo the comparisons. What do we notice?
• Below is the following code
• p1 = new Point(1,1);
• p2 = new Point(1,1);
Compare againp1andp2What do we observe? Execute the assignment.p1
= p2What happens to the object that was referenced byp2.
Exercise No. 8
Declare an arrayt1containing the values2, 7, 5, 21and-7Copyt1in a
tablet2Compare the tablest1andt2using the operator==and the
methodequals.
Object-oriented programming
License 2 in Computer Science --- Sheet No. 2
Classes and objects
We consider rectangles in the plane. Initially, we assume for
simplified so that the sides of the rectangles are parallel to the axes. A rectangle is
thus completely determined by the point at the bottom left and by its dimensions
horizontal and vertical.
Exercise No. 1 (Rectangle)
Define a classRectangleallowing the manipulation of such objects. Define three
constructors taking as parameters respectively 2 points, 1 point and 2 lengths
or 4 lengths.
Exercise No. 2
Write a methodsurfacewho calculates the area of the rectangle. Write a
methodtranslatewho moves a rectangle by moving the point at the bottom and to
left. What happens if multiple rectangles share the same point.
Exercise No. 3
Write a methodcontainswho tests if a given point (in parameter) is at
inside the rectangle. Write another methodcontainswho tests if a rectangle
given is inside the rectangle.
Exercise No. 4
Write a methodsameAswho tests the equality of two rectangles.
Exercise No. 5
Add to the classRectanglean attributenbrwho counts the number of objects of
the classRectangle.
Exercise No. 6
Write a methodhullwho calculates the bounding rectangle of a set of
rectangles. This method takes an array of rectangles as a parameter and returns
the smallest rectangle that contains all the rectangles in the array.
It is considered that a drawing consists of a set of rectangles.
Exercice n° 7 (Dessins)
Define a classDrawingEach object of this class contains an array of
rectangles whose size is fixed at the construction of the object. At first, a drawing does not
contains no rectangle. Write a methodaddwhich allows you to add a rectangle
to a drawing.
Exercise No. 8
Write methodssurfaceandtranslatefor the classDrawingThe surface of a
The area is the sum of the surfaces of its rectangles even if they overlap.
Translating a drawing involves translating each of its rectangles.
Exercise No. 9
Add to the classDrawinga methodhullwho calculates the bounding rectangle of
rectangles of the drawing. In order to be able to calculate this rectangle incrementally.
encompassing, add an attributehullRectto the classDrawingand modify the methods
so that they take this attribute into account.
Object-oriented programming
License 2 in Computer Science ---
Inheritance, method overriding and binding
late
We consider rectangles whose sides are no longer necessarily parallel.
on the axes. Such a rectangle is seen as a rectangle with parallel sides that would have
was tilted at a certain angle relative to the horizontal.
Exercise No. 1
En utilisant l'héritage, définir une classe SlantedRectangleallowing to manipulate
such objects. Define appropriate constructors.
Exercise No. 2
Define a methodrotatein the spirit of the methodtranslate.
Exercise No. 3
What methods does the class inherit?Slanted RectangleRedefine those that it
necessary.
Exercise No. 4
For each of the method calls below, say whether it will compile.
correctly and in which case, which method is actually called at runtime
?
Point p = new Point(1,2);
Rectangle r = new Rectangle(p, 2, 3);
Rectangle t = new SlantedRectangle(p, 2, 3);
SlantedRectangle s = new SlantedRectangle(p, 2, 3);
[Link]([Link]());
[Link](2);
[Link]([Link](p));
[Link]([Link]());
[Link](2);
[Link]([Link](p));
[Link]([Link]());
[Link](2);
[Link]([Link](p));
Exercise No. 5
Is the classDrawingpreviously defined can contain rectangles
Inclined? Are the methodssurface, containsandhullof the
classDrawingare still working properly?
Exercise No. 6
Define a methodString toString()in the classRectangleIs it actually
a definition or a redefinition? Is it necessary to redefine it in the
classSlanted Rectangle?
Exercise No. 7
Redefine the methodequalsin the classesRectangleandSlantedRectangle.
We consider the following class definitions
class A {
void f(A o) {
[Link]("void f(A o) in A");
}
}
class B extends A {
void f(A o) {
void f(A o) in B
}
}
Exercise No. 8
What does the following program fragment display?
A a = new A();
A ab = new B();
B b = new B();
a.f(a);
a.f(ab);
a.f(b);
ab.f(a);
ab.f(ab);
ab.f(b);
b.f(a);
b.f(ab);
b.f(b);
Exercise No. 9
We are now adding to the classB the following method
void f(B o) {
void f(B o) in B
}
Is it a redefinition or an overload? What then does the fragment display?
program of the'exercise 8?
Exercise No. 10
We finally add to the classA the following method
void f(B o) {
void f(B o) in A
}
Is it a redefinition or an overload? What then does the fragment display?
program of the'exercise 8?
Exercise No. 11
What does the following program fragment display?
[Link](a instanceof A);
[Link](ab instanceof A);
[Link](b instanceof A);
[Link](a instanceof B);
[Link](ab instanceof B);
[Link](b instanceof B);
Exercise No. 12
In the classroomRectanglea method has been definedboolean contains(Rectangle).
Should this method be redefined in the class?Slanted Rectangle? Which cases
are not covered by this redefinition? We then add a methodboolean
contains(SlantedRectangle)in the classesRectangleandSlanted RectangleWhat
are not always covered by these additions?
Exercise No. 13
We consider the following class definitions
class C {
char ch = 'C';
char getCh() { return ch; }
}
class D extends C {
char ch = 'D';
char getCh() { return ch; }
}
What does the following program fragment display?
C c = new C();
C cd = new D();
D d = new D();
[Link]([Link]);
[Link]([Link]());
[Link]([Link]);
[Link]([Link]());
[Link]([Link]);
[Link]([Link]());
Object-oriented programming
Licence 2 d'informatique --- Feuille n° 4
Interfaces and abstract classes
In addition to thepointsand of therectanglesseen
in previous sessions, we are interested
now to the discs. It is considered that a disc is determined by its center and
his/her ray.
Exercise No. 1
Define a classDiscwith appropriate constructors as well as
methodstranslate, surfaceandcontains.
In the previous sessions, a class had been [Link] allowed to
group rectangles.
Exercise No. 2
What is the best method to have drawings that can combine both
rectangles and disks. An interface can be usedFigure.
Exercise No. 3
The classDrawinghas methodstranslate, surfaceandcontainsCan she
implement the interfaceFigureWhat is the point of doing this?
2 Arithmetic expressions
We now consider arithmetic expressions formed from
real constants (floating-point numbers) and using the four arithmetic operations
usual operations (addition, subtraction, multiplication and division). Such an expression is
for example 3 + (4.7 + 2.3) * 5.
These arithmetic expressions are represented by binary trees. The nodes
the internal nodes of the tree contain the operators while the leaves of the tree
contain the constants. The left and right children of an internal node represent
the two left and right sub-expressions. The expression 3 + (4.7 + 2.3) * 5
the tree in the figure below.
FIG 1. The tree of the expression 3 + (4.7 + 2.3) * 5
The organization into interfaces and classes
Exercise No. 4
Define an interfaceArithmetic Expressionwho declares the functionalities of an expression
arithmetic. The only required feature is to be evaluable. Declare
consequently a methodevalthe good type.
To represent the expression, we will create objects for each of the nodes. These
objects will of course be instances of different classes depending on whether it is about
internal or leaf nodes.
Exercise No. 5
Define a classConstantto represent the constants of the expressions.
Exercise No. 6
Define four classesAddition, Subtraction, MultiplicationandDivisionfor the
arithmetic operations. It is noted that these four classes share a lot of
properties. How should we go about sharing the code?
Exercise No. 7
Redefine the methodtoStringto display expressions in infix notation.
Write methodsprefixandsuffixallowing to display the expressions in
prefix and suffix notation.
Exercise No. 8
What should be added for arithmetic expressions to be able to contain
variables like in the expression 3 * x + 7? How to define the
methodevalfor a variable?
Parseurs
The reading of an arithmetic expression is done through a parser. A
parser is an object capable of creating an arithmetic expression from a
string.
Exercise no. 9
Define an abstract classArithExprParserhaving two methodsparse. The
the first method takes a string as a parameter while the second
take aReader.
Exercise No. 10
Write a classPrefixParserallowing to read an arithmetic expression in
prefix notation.
Exercise No. 11 (difficult)
Write a classInfixParserallowing to read an arithmetic expression in
infix notation.
Object-oriented programming
License 2 in Computer Science --- Sheet No. 5
Exceptions
Exercise No. 1
Write a function that searches for an object in an array. If the object is found, the
function returns the first position where the object is found. Otherwise, the function raises
an exceptionNoSuchElementException.
Exercise No. 2
Write a function that searches for an object in a list. If the object is found, the
function returns the first cell where the object is located. Otherwise, the function raises an exception.
exceptionNoSuchElementExceptionOne can use an exception when the object
is found.
Exercise No. 3
Write a function that takes an array of strings as a parameter and returns the
integer value of the first string that can be read as an integer by the
methodparseIntIf no string can be read as an integer, the function
raise an exceptionNumberFormatException.
Exercise No. 4
What is the output of the code snippet below?
class Essai1Exception extends Exception {
Essay1Exception(String s) { super(s); }
}
class Essai2Exception extends Exception {
Essai2Exception(String s) { super(s); }
}
class Essai3Exception extends Essai1Exception {
Essay3Exception(String s) { super(s); }
}
class Sample {
static void throwEssais(int i) throws Exception {
try {
switch (i) {
case 1: throw new Essai1Exception("Essai1Exception from throwEssais");
case 2: throw new Essai2Exception("Essai2Exception from throwEssais");
case 3: throw new Essai3Exception("Essai3Exception from throwEssais");
default: throw new Exception("Throw test exception");
}
}
finally {
Finally de throwEssais
}
}
public static void main(String [] args)
{
for (int i = 1; i < 4; i++) {
try { throwEssais(i); }
catch (Essai3Exception e) { [Link]("Catch Essais3"); }
catch (Essai1Exception e) { [Link]("Catch Essais1"); }
catch (Exception e) { [Link]("Catch Exception"); }
finally { [Link]("Finally from main"); }
}
}
}
Object-oriented programming
Computer Science License 2 --- Sheet No. 6
Floats
Exercise No. 1
Write a Java program that copies a file. This program takes
on the command line the source file name and the destination file name.
Exercise No. 2
Write a Java program that displays the contents of a file in highlighting.
MAJUSCULE TOUS LES CARACTÈRES QUI PEUVENT L'ÊTRE.
Exercise No. 3
Write a Java program that writes an array and a list to a file and then reads them back.
these objects.
Exercise No. 4
Write a program that removes trailing whitespaces from a file.
Exercise No. 5
Write classesBitInputStreamandBitOutputStreamallowing for making
bit by bit inputs/outputs.
Object-oriented programming
License 2 in Computer Science --- Sheet No. 7
Collections
FIG 1 - The hierarchy of collections
FIG 2 - The hierarchy of maps
Exercise No. 1
Write a Java program that indexes the lines of a file. For each line
different, the program records the number of occurrences of this line in the
file.
Exercise No. 2
Revisit the previous exercise by indexing the words instead of indexing the lines.
Exercise No. 3
Write a Java program that sorts the lines of a file in lexicographical order.
Exercise No. 4
Repeat the previous exercise using the reverse order.
Exercise No. 5
Implement the interfaceListJava collections on the programmed lists to one
previous session. We will specifically implement the iterator using a class
internet.