0% found this document useful (0 votes)
4 views21 pages

Java Programming Guide for Beginners

This document is a TP booklet for Object-Oriented Programming using Java, aimed at 2nd year students at the University of Carthage. It includes various practical exercises and objectives focusing on Java language fundamentals, including compilation, execution, data types, conditional structures, and object-oriented concepts. The exercises encourage students to create classes, manipulate arrays, and implement methods to reinforce their understanding of Java programming.

Translated by

ScribdTranslations
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views21 pages

Java Programming Guide for Beginners

This document is a TP booklet for Object-Oriented Programming using Java, aimed at 2nd year students at the University of Carthage. It includes various practical exercises and objectives focusing on Java language fundamentals, including compilation, execution, data types, conditional structures, and object-oriented concepts. The exercises encourage students to create classes, manipulate arrays, and implement methods to reinforce their understanding of Java programming.

Translated by

ScribdTranslations
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

University of Carthage Department of Computer Science and Telecommunications

Higher Institute of Applied Sciences and Technology


Mature

TPbooklet
Object-Oriented Programming
Java Language

For the 2nd year studentsm̀eann´ee SEIoT/IRS

Aymen Ferjani
[Link]@[Link]

Academic year 2021/2022


SUMMARY
Page

TP1: Introduction to the Java Language 1

TP2: Introduction to the Java language (continued) 6

TP3: Basic concepts of the East´


the object 10

TP4: H´
Inheritance, Polymorphism and Abstract Class 13

TP5: ImplementationImplementation
´ of interfaces and exception handling 18
TPbooklet Department of Computer Science
and Telecoms
Object-Oriented Programming Level: 2m̀eSEIoT/IRS

TP1: Introduction to the Java language


Objectives

Compilation and execution of a Java program.


Input of values.
Passing values in command line (arguments).
Use of conditional and iterative structures.

1 Course Concepts
1.1 Compilation and execution of a Java program
Before starting to write Java code, it is necessary to install a JDK (Java Development Kit)
development Kit) in order to compile and execute our code.
The writing of a Java source code must be done in a file with the .java extension.
compiling this will generate another file with the .classet extension that contains some
pseudo-code. It is this file that is interpreted and executed by the Java Virtual Machine (JVM).
The JVM is an integral part of the JDK.
The compilation and execution of a Java file can be done in two different ways,
either with an IDE (Integrated Development Environment), or with a console.

1.1.1 With an IDE


Several Java IDEs exist on the market, such as NetBeans, Eclipse,
IntelliJ, etc. The writing of the code is often assisted there, as well as the compilation and execution which
are launched with a simple click.

1.1.2 In console mode


With the console, it is necessary to know the compilation command (for example javac)
because there are several compilers for Java. However, the execution is always performed
with the command java followed by the class name (without the extension). Here is an example of
compilation and execution of a Java file using the Linux console:

WorkFile$ javac [Link]


WorkFile$ java Hello
Hello everyone

1.2 Basic structure of a Java file


public class ClassName {
The attributes (properties) of this class
...
The methods of this class
...
The main method must be present in a single class of the project.
public static void main(String[] args) {
...
}
}

Aymen FERJANI page 1 of 19 AU: 2021/2022


TPPamphlet Department of Computer Science
and Telecoms
Object-Oriented Programming Level: 2eme
`
SEIoT/IRS

A Java source file contains one or more classes, but only one declared class.
public. The name of the file must correspond to the name of this class.
If the developed project consists of a single file, then it must necessarily contain
the main method.
In procedural programming, methods are viewed as functions.
The main method must always have the following signature:

public static void main(String[] args)

1.3 Primitive types of variables

Type Significance

int Integer between -231and 231-1.

double Real code on 64 bits.

char Character

boolean Bool´een

Remark
There are also the types byte, short, and long, which are integer types.
We also find the float type which represents a real number.
For character strings, it is preferable to use the String class (which is not a
primitive type).

1.4 Conditional and Iterative Structures


The conditional and iterative structures of the C language are taken up in Java. Thus,
find the conditional structures if and switch, but also the repetitive structures for, do
There is also a loop called foreach that is useful for iterating and displaying
the elements of a table or a collection:

int[]tab={20,-9,13,100,5};
Iterate and display each element of the array tab
for(int x: tab) {
[Link](x);
}

Aymen FERJANI page 2 of 19 AU: 2021/2022


TPpamphlet Department of Computer Science
and Telecoms
Object-Oriented Programming Level: 2eme
`
SEIoT/IRS

1.5 Entering values


Starting from Java version 5, it is possible to operate the input of values thanks to the class
Scanner. Here is an example:

import [Link]; // Import the Scanner class for input

public class Example Entry {


public static void main(String[] args) {
String chain;
intx;
doubley
// Creation of a Scanner object
Scanner lectureClavier=new Scanner([Link]);

Displaying a message before input


Enter a string:
Input a string of characters
string=[Link]();

Display a message before input


[Link]("Give an integer: ");
Input an integer
x=[Link]();

Display a message before input


Give a real number:
Input a real number
y=[Link]();
}
}

1.6 Passing values in command line (arguments)


Let the following classTest be:

public class Test{


public staticvoidmain(String[]args) {
[Link]("The first argument is " + args[0]);
[Link]("The second argument is " + args[1]);
[Link]("The third argument is " + args[2]);
}
}

Arguments are passed to this program in console mode as follows:

WorkFile$ java Test hello158hello


The first argument is hello
The second argument is 158
The third argument is hello

Aymen FERJANI page 3 of 19 AU: 2021/2022


TPbooklet Department of Computer Science
and Telecommunications

Object-Oriented Programming Level: 2m̀eSEIoT/IRS

2 practical exercises
For each exercise, a new project will be created.

Exercise 1
Create the class Hello with the following code, then test it:

public class Hello {


public static void main(String[] args) {
Hello everyone
}
}

Exercise 2
Create the class Ex2, then:
´
1. Write the method public int addition(int x, int y, int z) that returns the sum of 3
integers x, y, z.
2. Add the method public int max(int x, int y, int z) that returns the maximum between
3 integers x, y, z.
3. Add the method public boolean prime(int x) that verifies if x is a number
first or not.
4. Test these 3 methods as follows:

import [Link];
public class Ex2 {
Definitions of the methods for questions 1, 2, and 3
...
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
inta, b, c;
Give 3 integers:
a = [Link]();
b = [Link]();
c = [Link]();
Ex2 obj=newEx2();//Creation ofan instance of the Ex2 class
[Link](a+"+"+b+"+"+c+"="+[Link](a, b, c));
[Link]("The maximum of the 3 integers is " + [Link](a, b, c));
if([Link](a)) {
[Link](a + " is a prime number");
}
else{
[Link](a + " n");is not a prime number);
}
}
}

Aymen FERJANI page 4 of 19 AU: 2021/2022


TPbooklet Department of Computer Science
and Telecoms
Object-Oriented Programming Level: 2eme
`
SEIoT/IRS

Exercise 3
Ẃrite a program that calculates and displays the sum and product of 4 integers provided.
arguments.
For each argument, use the predefined method [Link](x) to obtain a
entire from this argument.

Exercise 4
´
Write a program to read a positive integer entered in the command line
and display it in binary format.

Aymen FERJANI page 5 of 19 AU: 2021/2022


TPPamphlet Department of Computer Science
and Telecoms
Object-Oriented Programming Level: 2m̀eSEIoT/IRS

TP2: Introduction to the Java language (continued)

Objectives

Input of values.
Passing values in command line (arguments).
Utilization of conditional and iterative structures.
Manipulation of the tables.

1 Course Concepts
1.1 Creation and manipulation of a fixed-size array
Creating a fixed-size array is done by the following instruction:

type[]nomTableau=newtype[NombreElements];

Here, "type" refers to a base type or a class. Here is an example:

Creation of an array of 5 integers


int[] tab = new int[5];

You can also create and initialize an array at the same time. Example:

Creation and initialization of an array of 3 integers


int[]x={9,45,-22};

The manipulation of arrays in Java is identical to that of the C language, with


the advantage of being able to know the size of an array thanks to the length attribute.

1.2 Example
// Cr´eation et initialisation d'un tableau de 4 r´eels
double[]tab={12.0,2.6,0.5,100.11};

tab[2] = -16.125;// modify theelement of index 2

Display of the elements of the array


// [Link] returns the size of the array
for(int i = 0; i < [Link]; i++) {
[Link](tab[i]);
}
/* or with a foreach loop:
for(double x : array) {
[Link](x);
} */

Aymen FERJANI page 6 of 19 AU: 2021/2022


TPIssue Department of Computer Science
and Telecommunications

Object-Oriented Programming Level: 2eme


`
SEIoT/IRS

2 Practical exercises
Exercise 1
Écrire la classeAnn´eeavec une m´ethode qui permet de d´eterminer si une ann´ee est bissextile
A year is a leap year if we have one of the following two cases:
The year is divisible by 4 and not divisible by 100.
The year is divisible by 400.

Exercise 2
Ẃrite the DayOfWeek class with a method that, given an integer representing a
day of the week (between 1 and 7), display the corresponding name of that day.
Examples:
jour = 1 =>Affichage : ”C’est lundi”
jour = 2 =>Affichage : ”C’est mardi”

Exercise 3
Ẃrite a program that reads 2 arguments which are a positive integer (denoted n) and
a string of characters, then displays this string n times (on different lines).
For example, if the user passes the arguments '5' and 'Hello', we will have the following output
vant:

Hello once

Hello2times

Hello three times

Hello4times

Hello 5 times

Exercise 4
Ẃrite the Perfect class with a method that takes a positive integer and indicates if it is.
is a perfect number or not. A perfect number is equal to the sum of its proper divisors.
(except for himself).
Examples of perfect numbers:
6=1+2+3
28 = 1 + 2 + 4 + 7 + 14
496 = 1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 + 248

Exercise 5
Ẃrite a program that calculates and displays the sum of the integers passed as arguments.

Exercise 6
Ćreate the Pair class with 2 methods. The first allows you to fill an array of integers.
The second displays the even elements of an array of integers.

Aymen FERJANI page 7 of 19 AU: 2021/2022


TPbooklet Department of Computer Science
and Telecoms
Object-Oriented Programming Level: 2m̀eSEIoT/IRS

import [Link];
public class Pair{
public void remplirTab(int[] t)
/* fill t with entered integers */
public void displayPair(int[] t)
/* display the even elements of t */

public static void main(String[] args) {


intn;
Scanner input = new Scanner([Link]);
do{
[Link]("Enter the size of the array (>=2): ");
n=[Link]();
}
while(n < 2);
inttab[] = new int[n]; // Creation ofa table of n integers
Pair p=newPair();//Creation ofan instance of the Pair class
[Link](tab);
[Link]("Displaying the even elements of the array:");
[Link](tab);
}
}

Exercise 7
Ẃrite the class Tabayant with 3 methods. The first one allows you to create an array of integers of
size (to be entered) and to fill it. The second displays the elements of an array of integers.
third returns the largest element of an array of integers.

import [Link];
public class Tab{
public static int[] creationTableau() {
1. Enter the size of the array, creation of the array
2. fill the table from entered integers
3. return this table */

public static void displayArray(int[] t)


/* display the elements of the array t */

public static int maxTableau(int[] t)


return lthe largest element of t}

public static void main(String[] args) {


Tab tab=newTab();//Creation dan instance of the Tab class
intt[] = [Link]();
[Link]("Displaying the elements of the array:");
[Link](t);
[Link]("The max of the array is " + [Link](t));
}
}

Aymen FERJANI page 8 of 19 AU: 2021/2022


TPbooklet Department of Computer Science
and Telecommunications

Object-Oriented Programming Level: 2eme


`
SEIoT/IRS

Exercise 8
Ẃrite a program that creates and fills an array of real numbers from the arguments, then
reverse this table and display its elements.

Exercise 9
Ẃrite a program that inputs and fills an array of strings, then inputs
a string and indicate whether this string is in the array. In the case where the string exists,
the program must also display its position in the table.
Note: Use the method [Link](string) to compare between two strings.
Examples:

String ch1="bonjour", ch2="bonjour", ch3="Bonjour";


[Link](ch2) // returns true
[Link](ch3) // returns false

Exercise 10
Ẃrite a program that allows entering and filling the elements of an array.
of integers, then performs the selection sort in ascending order on this array, and finally displays
the painting.
Principle:
For each element tab[i], determine the index of the smallest element to the right of tab[i].
(smaller than tab[i]), then swap tab[i] and tab[min]. If we do not find an element more
small quetab[i], so no permutation is made.

Aymen FERJANI page 9 of 19 AU: 2021/2022


TPBooklet Department of Computer Science
and Telecommunications

Object Oriented ProgrammingLevel: 2eme


`
SEIoT/IRS

TP3: Basic Concepts of Object-Oriented


Objectives

Create classes, instantiate objects and call methods.


Understand the principle of data encapsulation.

1 Practical exercises
Exercise 1
We want to model a point in a plane having an orthonormal reference.
´
1. Write the Point class containing the necessary attributes as well as a constructor taking
parameters.
2. Add another constructor without parameters that initializes a point at the position (0,0).
3. For each attribute, add a getter method (get) to return the value of
the attribute, and a mutator method (set) to modify the value of the attribute.
4. Add the method public void modifyCoord(double x, double y) which
allows to modify the coordinates of a point.
´
5. Write the method public boolean samePosition(Point p) that verifies if a point has the
same coordinates as point p.
´
6. Write the method public boolean isSymmetric(Point p) that verifies if a point is
symmetric to point p with respect to the origin of the coordinate system (0,0).
7. Add the method public double distance(Point p) allowing to calculate and
return the distance between a point and point p according to the following formula:
(x−xp )2+ (y−yp )2
p
Use the predefined methods [Link](x, 2) to calculate the square of x and [Link](x)
for the square root of an x.
8. In the same package, create the class TestPoint containing the main method to
test the methods of the class Point:
public class TestPoint
{
public staticvoidmain(String[]args)
{
Point p1=newPoint(5,3);
Point p2=newPoint();
[Link]("p1("+[Link]()+","+[Link]()+")");
[Link]("p2("+[Link]()+","+[Link]()+")");
[Link](5,10);
[Link]("p2("+[Link]()+","+[Link]()+")");
if(![Link](p2))
p1 and p2 ndo not have the same position);
Point p3=newPoint(-5,-3);
[Link]("p3("+[Link]()+","+[Link]()+")");
if([Link](p3))
p1 and p3 are symmetric
[Link]("The distance between p1 and p2 is " + [Link](p2));
}
}

Aymen FERJANI page 10 of 19 AU: 2021/2022


TPbooklet Department of Computer Science
and Telecoms
Object-Oriented Programming Level: 2eme
`
SEIoT/IRS

Exercise 2
We want to model a date characterized by a day, a month, and a year.
´
1. Write the Date class with the necessary attributes as well as a constructor that
initialize a date.
2. For each attribute, add a getter method (get) to return the value of
the attribute, and a mutator method (set) to modify the value of the attribute.
3. Redefine the method public String toString() that returns a date in the form:
day/month/year
4. Add the method private boolean leapYear() that verifies if the year of a date
is a leap year or not. A year is a leap year in the following cases:
It is divisible by 4 and not by 100.
It is divisible by 400.
5. Add the method private int numberOfDaysInMonth() that returns the number of days
of the month (for example: month = 1 ⇒ number of days = 31). Use the previous method.
´
6. Write the public boolean isValid() method to verify if a date is
correct or not. Use the previous method.
7. Add the public boolean moreRecent(Date d) method that indicates if a date is
more recent than the date of.
8. In the same package, create the TestDate class containing the main method to test.
the methods of the Date class:
public class TestDate
{
public static void main(String[] args)
{
Date d1=new Date(28,2,2018);
if([Link]())
[Link](d1 + " is valid");
Date d2=newDate(30,2,2017);
if(![Link]())
[Link](d2+" nis not valid);
Date d3=new Date(17,10,2020);
if([Link](d1))
[Link](d3 + " is more recent than " + d1);
}
}

Exercise 3
We want to model a stack of integers stored in the form of an array.
1. Define the Stack class with attributes an integer size (the size of the stack), a
another integer named tailleMax (the maximum size of the stack, a constant) and an array
of integers named p.
2. Add a constructor, taking an integer parameter named, which initializes size to zero
set the sizeMax, then create the array with the size sizeMax.
3. Add the accessor method public int getSize() that allows returning the size of
the battery.
´
4. Write the method public boolean isEmpty() that indicates whether the stack is empty or not.
5. Add the method public boolean isFull() that indicates whether the stack is full or not.

Aymen FERJANI page 11 of 19 AU: 2021/2022


TPbooklet Department of Computer Science
and Telecoms
Object-Oriented Programming Level: 2eme
`
SEIoT/IRS

6. Add the method public void display() that displays the elements of the stack.
´
7. Write the method public void empiler(int x) that adds x to the end of the stack and increments
Remove 1 if the stack is not full. Display a message if the stack is already full.
´
8. Write the method public void depile() which removes the last element (it is enough to
decrement the size by 1) if the stack is not empty. Display a message if the stack is already
see.
9. In the same package, define the TestPile class with the main method and test it.
methods of the class Stack.

Exercise 4
We want to model a linked list composed of several nodes where each node
contains an integer.
1. Write ´ the Node class with an integer attribute and a reference to the node.
following namedfollowing(nodeType).
2. Add a constructor to the Node class, taking an integer parameter, which initializes val.
to the value of the parameter. The following reference will point to null.
3. Add accessor and mutator methods to the Node class to retrieve
and to modify the attributes of this class.
4. Add, in the same package, the class List with a reference as an attribute on the
tˆete de liste nomm´eetˆete(typeNoeud) et un entiertaillequi est la taille de cette liste.
5. Add a constructor to the List class, without parameters, that initializes the head reference.
.orezotgnilNlu
6. Add accessor and mutator methods to the List class to retrieve the
head and size and modify only the head.
7. Add the method public boolean isEmpty() which indicates whether the list is empty or not.
8. Add the public void display() method that traverses the list and displays the values of
its nodes.
9. Add the method public void addInteger(int val) that adds a node, having the
integer value, at the end of the list and incremented by 1.
´
10. Write the method public void deleteInteger(int val) that deletes the first node
met from the head having the value val, and decrement detailed by 1 if this node has been
found.
11. In the same package, add the TestList class containing the main method with the
following code:
List lst=newList();
[Link](15);
[Link](-9);
[Link](5);
[Link](-26);
[Link](42);
[Link]();
Removing -26 then 15:
[Link](-26);
[Link](15);
[Link]();
Adding 103:
[Link](103);
[Link]();
[Link]("La liste contient "+[Link]()+" noeuds");

Aymen FERJANI page 12 of 19 AU: 2021/2022


TPbooklet Department of Computer Science
and Telecommunications

Object-Oriented Programming Level: 2eme


`
SEIoT/IRS

TP4: Heritage, Polymorphism and Abstract Class


Objectives

Utilization of heritage.
Understand polymorphism.
Understand the usefulness of an abstract class.
Creation and use of a dynamic table.

1 Course concepts
1.1 Creation and manipulation of a dynamic array
To create a resizable array, you can use the ArrayList class:
Import the ArrayList class at the beginning of the file
import [Link];
...
Creation of a dynamic array of String
ArrayList<String>tab=newArrayList<>();

It should be noted that this class does not allow the creation of arrays of primitive types.
To remedy this lack, we can use wrapper classes.

1.2 Wrapper Classes


Wrapper classes encapsulate primitive types. Each primitive type
therefore has its class that allows it to behave like an object:

Primitive type Wrapper class


boolean Boolean
character Character
byte Byte
short Short
int Integer
long Long
float Float
double Double

1.3 Some methods of the ArrayList class


Here are some practical methods of the ArrayList class:

Aymen FERJANI page 13 of 19 AU: 2021/2022


TPbooklet Department of Computer Science
and Telecoms
Object-Oriented Programming Level: 2eme
`
SEIoT/IRS

Method Role

add(Object) Add the object at the end of the table.

add(inti, Objecte) Add the object to the specified index of the array.

remove(inti) Remove the element with the index from the array.

size() Return the size of the array.

get(inti) Return the element of the array with the index i.

set(int, Object) Affects the object to the indexed table.

1.4 Example
Import the ArrayList class at the beginning of the file, just after the package.
import [Link];
...
ArrayList<String> tab = new ArrayList<>();

Hello
Hello
[Link](0,"Hello");// adds to the beginning of the array
Goodbye
Thank you

[Link](2);// remove lelement of index 2 ("hello")

for(int i = 0; i < [Link](); i++) { // loops through the array


[Link]([Link](i));// displays each element
}

2 practical exercises
Exercise 1
A company wants to manage its employee list with a Java application. There is
mainly two types of employees: managers and workers.
1. Knowing that an employee is described by their identification number, name, age, and salary, define
the Employee class having a constructor with parameters that initializes all its attributes.
2. Add a static integer attribute initialized to 0 and that will be incremented by 1
Each time an employee is created.
3. Add the methods getAge, getSalary and setSalary, as well as the static method
getName
4. Redefine the public method toString that returns the information of an employee according to
this form:
matricule nom,a^ge ans, salaire dt
Example: E10268 Ahmed SASSI, 34 years old, 1200 dt

Aymen FERJANI page 14 of 19 AU: 2021/2022


TPbooklet Department of Computer Science
and Telecoms
Object-Oriented Programming Level: 2eme
`
SEIoT/IRS

5. Define, in the same package, the Worker class knowing that a worker has the same
properties of an employee. Add a constructor with parameters that initializes the values
attributes.
6. Define, in the same package, the class Frame knowing that in addition to the properties of a
employee, each executive has a role. Add a constructor with parameters that
initialize the values of the attributes.
7. Redefine the method toString in the Worker class by adding the word 'Worker' to it.
end of the reversed chain. Example:
E10270 Mounir DRIDI,36ans,900dt, Ouvrier

8. Redefine the toString method in the Frame class by adding the frame's function.
the end of the returned chain. Example:
E10268 Ahmed SASSI,34ans,1200dt, Analyste

9. The company has decided to increase the salaries of its employees according to this formula:
For the workers, a raise of 100 dt.
— For the executives:
An increase of 200 dt if the age is below 35 years.
A 300 dt increase if the age is between 35 years and 45 years.
An increase of 400 dt for the others.
Declare the public abstract method increase in the Employee class. Thus, the
class Employee will become abstract, and the method increase must be defined in
the working class and the managerial class.

10. In order to test these classes and their methods, create, in the same package, the class
TestEmployee having the method main with the following code:
Employee[] list = new Employee[5];
liste[0] =newCadre("E10268","Ahmed SASSI",34,1200,"Analyste");
liste[1] =newCadre("E10269","Ridha DRIDI",46,1350,"Comptable");
liste[2] =newOuvrier("E10270","Mounir DRIDI",36,900);
liste[3] =newOuvrier("E10271","Alia ARBI",29,850);
liste[4] =newCadre("E10272","Amal TOUATI",38,1850,"Directeur RH");

for(int i = 0; i < [Link]; i++) {


list[i].increase();
[Link](liste[i]);
}

[Link]("We have created " + Employé.getNombre() + " employees");

11. Transform the table list into ArrayList.

Aymen FERJANI page 15 of 19 AU: 2021/2022


TPbooklet Department of Computer Science
and Telecoms
Object-Oriented Programming Level: 2eme
`
SEIoT/IRS

Exercise 2
We want to model the concepts of vehicle, car, and airplane.
Define the Vehicle class which has attributes that are valid for any type.
de v´ehicule: son mod`ele, son ann´ee d’achat, son prix d’achat et son prix courant.
2. Add a constructor with 3 parameters (model, year of purchase, and purchase price) that
initialize all these attributes. The current price will be set to the purchase price.
3. Redefine the toString method that returns the information of a vehicle in the specified format.
next:
mod`ele, ann´eeAchat, prixAchat dt, prixCourant dt
//Exemple: Peugeot 206, 2005, 16000 dt, 12000 dt

4. Add the accessor and mutator methods getPurchaseYear, getPurchasePrice


setCurrentPrice.
5. Define, in the same package, the class Car which inherits from Vehicle and has the
the following additional attributes:
number of doors
scale power
mileage
Add a constructor with parameters that initializes all the attributes. Again, the
The current price will be set at the purchase price.

6. Define, in the same package, the class Aircraft which also inherits from Vehicle and having
the following additional attributes:
number of passengers
flight hours
Add a constructor with parameters that initializes all the attributes. Here too, the
the current price will be set at the purchase price.

7. Redefine the toString method in the Car class by adding the relevant information.
to the car at the end of the returned chain. Example:
PEUGEOT206,2005,20000.0dt,10000.0dt,4portes,5cv,200000km

8. Redefine the method toString in the Airplane class by adding the specific information.
"to the plane" at the end of the returned chain. Example:
CESSNA CITATION II,1982,4000000.0dt,2200000.0dt,9passagers,15300heures

9. Declare the abstract method public modifyCurrentPrice(int currentYear) in


the class Vehicle.
10. Define the previous method in the two subclasses Car and Plane so that
calculate the current price based on certain criteria, and update the attribute
corresponding to the current price:
For a car, the current price is equal to the purchase price.
-2% for each year since the purchase until the current year.
-1% for every 10,000 km traveled.
For an airplane, the current price is equal to the purchase price minus 3% for each
slice of 1000 flight hours, and less than 1% for each year since the purchase until
Current year.
Attention, in these two methods, if the price becomes negative, we then set it to zero.
Aymen FERJANI page 16 of 19 AU: 2021/2022
TPbooklet Department of Computer Science
and Telecommunications

Object-Oriented Programming Level: 2eme


`
SEIoT/IRS

11. In order to test these classes and their methods, create, in the same package, the class
Test vehicle with the following method code:
ArrayList<Vehicle> tab = new ArrayList<>();

[Link](newCar("PEUGEOT 206", 2005, 20000, 4, 5, 200000));


[Link](newVoiture("SUZUKI SWIFT",2016,30000,4,4,38000));
[Link](newCar("FIAT 500",2010,20000,4,4,150000));
[Link](newPlane("CESSNA CITATION II",1982,4000000,9,15300));
[Link](newAirplane("DAHER-SOCATA TBM 700",2001,3500000,5,18000));

for(Vehicle v: tab) {// foreach loop


[Link](2020);
[Link](v);
}

Aymen FERJANI page 17 of 19 AU: 2021/2022


TPbooklet Department of Computer Science
and Telecoms
Object-Oriented Programming Level: 2eme
`
SEIoT/IRS

TP5: Implementation of interfaces and management of


exceptions
Objectives

Create and implement interfaces.


Manage exceptions.

1 Practical exercise
We want to implement the following class diagram:

By respecting the data from the diagram:


1. Create the Addable interface.
2. Define the class Reel which represents a real number.
The method plus(Object o) should return a new object of type Real that represents
the sum of the two reals (the current object and the parameter o).
3. In the method racineCarree() of the class Reel, raise a new exception (of type
Exception) with the message 'Unable to calculate the root of the negative number n' (n`a
replace with the value of the real) when the number is negative.
4. Define the Complex class that represents a complex number.
The method toString() must return the following representation of the complex number:

(pReal + pImaginary*i)
(5.2 + 3.6*i)

The method plus(Object o) must return a new object of type Complex.


represents the sum of the two complex numbers (the current object and the parameter o).
5. In order to test these classes and their methods, create the Test class with the main method.
with the following code:

Aymen FERJANI page 18 of 19 AU: 2021/2022


TPbooklet Department of Computer Science
and T´el´ecoms
Object Oriented ProgrammingLevel: 2m̀eSEIoT/IRS

Complex c1=newComplex(2,3.6);
Complex c2=newComplex(5.1,10.22);
Complex c3 = (Complex)[Link](c2);
[Link](c1 + " + " + c2 + " = " + c3);

Reel r1=newReel(9.0);
Reel r2=newReel(-2.1);
try{
[Link]("The square root of " + r1 + " is " + [Link]());
}
catch(Exception e) {
[Link]([Link]());
}
try{
[Link]("The square root of " + r2 + " is " + [Link]());
}
catch(Exception e) {
[Link]([Link]());
}
Reel r3 = (Reel) [Link](r2);
[Link](r1 + " + " + r2 + " = " + r3);

6. Define the custom exception ExceptionValeurNegative with the redefined method


public String getMessage()qui devra retourn´ee le message ”Impossible d’effectuer la
square root of the negative number n" (n to be replaced by the value of the real).
Modify the method squareRoot() of the Real class so that it raises this exception.
when the number is negative.
Also modify the method in the Test class by replacing Exception with
NegativeValueException.

Aymen FERJANI page 19 of 19 AU: 2021/2022

You might also like