0% found this document useful (0 votes)
15 views6 pages

Corrections d'Exercices Java et POO

correction java

Uploaded by

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

Corrections d'Exercices Java et POO

correction java

Uploaded by

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

Correction des Exercices - Examen Java

& MySQL
Exercice 1: Niveau 1 - Facile
Créer une classe Java nommée Utilisateur qui a comme attributs :
- ID : entier
- nom : chaîne de caractères

La classe dispose d'un constructeur qui initialise les deux attributs. Le constructeur lève une
exception ErrUtilisateur si le nombre de caractères du nom dépasse 50. La classe doit aussi
avoir les getters et setters nécessaires. Finalement, créer une classe Test pour tester la
création d'objets Utilisateur.

Voici le code en Java :

public class Utilisateur {


private int id;
private String nom;

public Utilisateur(int id, String nom) throws ErrUtilisateur {


if ([Link]() > 50) {
throw new ErrUtilisateur("Le nom dépasse 50 caractères");
}
[Link] = id;
[Link] = nom;
}

public int getId() {


return id;
}

public void setId(int id) {


[Link] = id;
}

public String getNom() {


return nom;
}

public void setNom(String nom) throws ErrUtilisateur {


if ([Link]() > 50) {
throw new ErrUtilisateur("Le nom dépasse 50 caractères");
}
[Link] = nom;
}
}

class ErrUtilisateur extends Exception {


public ErrUtilisateur(String message) {
super(message);
}
}

public class Test {


public static void main(String[] args) {
try {
Utilisateur u1 = new Utilisateur(1, "Jean Dupont");
[Link]("Utilisateur créé: " + [Link]());
Utilisateur u2 = new Utilisateur(2, "Nom très très très très très long qui dépasse 50
caractères");
} catch (ErrUtilisateur e) {
[Link]([Link]());
}
}
}
Exercice 2: Niveau 2 - Moyen
Nous avons deux catégories d'employés :
- Catégorie A (CommissionEmployee): employés payés en pourcentage des ventes.
- Catégorie B (BasePlusCommissionEmployee): employés avec salaire de base plus
pourcentage des ventes.

Tâches :
1. Créer une classe abstraite Java nommée Employee avec des sous-classes pour les deux
catégories.
2. Créer une classe Test avec une fonction main() pour créer un tableau d'employés.
3. Expliquer le concept de la programmation orientée objet en relation avec cet exercice.
4. Modifier la classe Employee pour qu'elle puisse être utilisée dans une
HashSet<Employee>.

Voici le code en Java :

public abstract class Employee {


private String nni;
private String prenom;
private String nom;

public Employee(String nni, String prenom, String nom) {


[Link] = nni;
[Link] = prenom;
[Link] = nom;
}

public String getNni() {


return nni;
}

public String getPrenom() {


return prenom;
}

public String getNom() {


return nom;
}

public abstract double calculerSalaire();


}
class CommissionEmployee extends Employee {
private double ventesMensuelles;
private double pourcentage;

public CommissionEmployee(String nni, String prenom, String nom, double


ventesMensuelles, double pourcentage) {
super(nni, prenom, nom);
[Link] = ventesMensuelles;
[Link] = pourcentage;
}

@Override
public double calculerSalaire() {
return ventesMensuelles * pourcentage;
}
}

class BasePlusCommissionEmployee extends CommissionEmployee {


private double salaireDeBase;

public BasePlusCommissionEmployee(String nni, String prenom, String nom, double


ventesMensuelles, double pourcentage, double salaireDeBase) {
super(nni, prenom, nom, ventesMensuelles, pourcentage);
[Link] = salaireDeBase;
}

@Override
public double calculerSalaire() {
return salaireDeBase + [Link]();
}
}

public class Test {


public static void main(String[] args) {
Employee[] employes = new Employee[3];
employes[0] = new CommissionEmployee("123", "Jean", "Dupont", 10000, 0.06);
employes[1] = new BasePlusCommissionEmployee("124", "Marie", "Curie", 8000, 0.04,
2000);
employes[2] = new CommissionEmployee("125", "Albert", "Einstein", 12000, 0.05);

for (Employee e : employes) {


[Link]("Salaire de " + [Link]() + " " + [Link]() + ": " +
[Link]());
}
}
}

Explication des concepts de la POO :

La programmation orientée objet (POO) permet de structurer le code en utilisant des objets
représentant des entités du monde réel. L'héritage, par exemple, permet de créer des
classes spécialisées à partir de classes plus générales, comme dans cet exercice avec
Employee et ses sous-classes. L'encapsulation est utilisée pour protéger les données des
objets, et le polymorphisme permet d'utiliser des objets de différentes classes de manière
interchangeable.

Pour utiliser la classe Employee dans une collection HashSet<Employee>, il serait


nécessaire d'implémenter les méthodes hashCode() et equals() dans la classe Employee.
Cela permettrait de garantir que deux objets Employee égaux soient traités comme
identiques dans le HashSet.
Exercice 3: Niveau 3 - Difficile
1. Modélisation entité-association pour la gestion des données administratives de la
Mauritanie.

Voici la structure des tables :


Table Wilaya (codeWilaya, nomWilaya)
Table Moughataa (codeMoughataa, nomMoughataa, codeWilaya)
Table Commune (codeCommune, nomCommune, codeMoughataa)

Common questions

Powered by AI

Each subclass in the Employee class hierarchy implements polymorphism by overriding the abstract method calculerSalaire, providing a specific computation of salary based on the nature of the subclass. CommissionEmployee calculates the salary as a percentage of sales, while BasePlusCommissionEmployee includes a base salary plus the commission . Polymorphism enables the main program to treat all employee types uniformly via Employee references while invoking subclass-specific implementations of calculerSalaire. This design allows the addition of new employee types with distinct salary calculations without modifying the existing code, enhancing flexibility and maintainability .

Encapsulation and polymorphism enhance error handling within the Java example by structuring the code to manage and respond to errors efficiently while maintaining data integrity. Encapsulation ensures that data within classes (like Utilisateur) is accessed and modified only through controlled interfaces (getters and setters), incorporating checks like name length validation and preventing invalid states by triggering exceptions (ErrUtilisateur) when constraints are violated . This tightly controlled access reduces the risk of erroneous data manipulation and simplifies debugging if errors occur. Polymorphism allows different employee subtypes to be handled uniformly while ensuring that their specific methods, like calculerSalaire, are invoked correctly. This trait, alongside validated encapsulation, allows error handling to be uniformly applied across diverse object types, centralizing error management and greatly simplifying the process of identifying and rectifying logic errors within polymorphic behavior .

Inheritance plays a crucial role in the design of the Employee hierarchy by facilitating code reuse and system extensibility. The Employee superclass provides a set of properties and methods (such as personal data and the abstract calculerSalaire method) that are common across all employee types. Each subclass, such as CommissionEmployee and BasePlusCommissionEmployee, extends the Employee class, inheriting these shared elements while also introducing specific attributes and behaviors, such as different salary calculation methods . This reduces redundancy, as common code is written once in the superclass. System extensibility is enhanced, as new types of employees can be added by simply creating new subclasses, inheriting core functionality from Employee, and implementing additional specific features, all without the need to modify existing class logic .

Organizing code as a hierarchy of classes, as demonstrated by the Employee example, offers several advantages. It promotes code reuse by allowing shared behavior to be defined in a superclass and reused in subclasses; this reduces redundancy and enhances maintainability. Hierarchies also facilitate scalability; new employee types can be added with specific behavior by creating new subclasses without altering existing code . Additionally, polymorphism provides flexibility, enabling objects of different subclasses to be used interchangeably, thereby simplifying code in operations involving collections of related objects. This structure also supports abstraction, making complex systems more comprehensible by focusing on high-level interclass relationships instead of low-level implementation details .

The implementation of the calculerSalaire method differs between CommissionEmployee and BasePlusCommissionEmployee by addressing the specific composition of an employee's salary. The CommissionEmployee overrides the method to compute salary based solely on a percentage of sales, whereas the BasePlusCommissionEmployee calculates salary by adding a base salary to the commission derived from their sales . This implies that each subclass tailors the generic behavior defined in the Employee superclass to meet its specific operational needs, showcasing the concept of method overriding in OOP. It demonstrates subclass-specific behavior where the overarching contract (i.e., how an employee calculates salary) remains uniform across the hierarchy, but the method execution is customized depending on the subclass specifics .

The provided Java code demonstrates several object-oriented programming (OOP) concepts through the inheritance hierarchy of the Employee class and its subclasses CommissionEmployee and BasePlusCommissionEmployee. Firstly, inheritance is demonstrated by the subclasses deriving from the Employee superclass, allowing code reuse and organization . Encapsulation is evident as private fields are protected and accessed through public methods, ensuring data integrity . Polymorphism allows the use of Employee references to point to subclass instances, enabling dynamic method invocation; for example, the calculerSalaire method is overridden in each subclass to provide specific functionality . The code could be further enhanced for hash-based collections such as HashSet by implementing hashCode() and equals() methods in the Employee class, which is necessary for checking object equality and handling hash collisions .

The Java class Utilisateur protects its objects from having attributes with invalid values by implementing constraints in its constructor and setter method. Specifically, it throws a custom exception, ErrUtilisateur, if the name attribute exceeds 50 characters. During object creation in the constructor and when updating the name using the setNom method, the length of the name is checked, and if it exceeds the limit, the ErrUtilisateur exception is triggered to alert the programmer of invalid input, effectively preventing the creation of instances with an excessively long name .

The Utilisateur class in Java throws the ErrUtilisateur exception to enforce a constraint on the maximum length of the name attribute, which is set to 50 characters. This error-handling approach ensures that no Utilisateur object is created or modified with a name exceeding this limit, preserving data validity and preventing potential data storage issues . By throwing and handling this exception at runtime, the approach provides a clear mechanism for alerting developers or users to incorrect input early in the execution process. This contributes to more robust programs by preventing invalid object states and potentially facilitating the display of meaningful error messages to the user or even triggering corrective workflows .

Encapsulation in the Java Utilisateur class is achieved by making attributes private and exposing them through public getter and setter methods. This approach restricts direct access to the internal state of Utilisateur objects, allowing controlled modification of the attributes and ensuring only valid values are assigned. For instance, the setNom method checks the length of the name, raising an exception if it is over 50 characters . A notable exception to encapsulation in the code is the non-private class Test, which directly instantiates the Utilisateur objects; however, it adheres to validation logic by handling exceptions rather than bypassing the validation .

Overriding the hashCode() and equals() methods in the Employee class is necessary for maintaining data integrity within a HashSet. The HashSet relies on these methods to ensure that each object is unique within the collection. The equals() method is used to check whether two objects are considered equivalent, while the hashCode() method is used to determine the object's bucket location in the hash table. If these methods are not overridden, the default implementation from the Object class would only compare memory addresses rather than logical attribute equality. This means that logically equivalent Employee objects may not be treated as such, leading to potential duplicates in the HashSet and violating the set's property of unique items .

You might also like