Version without JavaScript, read-only: workshops, quizzes and running code are not available here. Full version · Catalogue · Sign in
Sequence
Encapsulation: getters and setters
Core exercise
Make the three attributes of Personne private, then add the getters getNom(), getPrenom(), getAge() and the setters setNom(String), setPrenom(String), setAge(int). setAge must reject a negative age (it then leaves the age unchanged).
A workshop goes here: you write and run code in it. It requires JavaScript.
Starting code
Personne.java
public class Personne {
// TODO : passer ces attributs en private
String nom;
String prenom;
int age;
public Personne(String nom, String prenom, int age) {
this.nom = nom;
this.prenom = prenom;
this.age = age;
}
// TODO : getNom, getPrenom, getAge
// TODO : setNom, setPrenom, setAge (qui refuse un age negatif)
public void afficherDetails() {
System.out.println(prenom + " " + nom + ", " + age + " ans");
}
}
Exercices.java
public class Exercices {
public static void main(String[] args) {
// Une fois les getters et setters ecrits, remplacez ces lignes par :
// Personne p = new Personne("Dupont", "Jean", 18);
// p.setAge(-5);
// System.out.println("age apres setAge(-5) : " + p.getAge());
System.out.println("Completez Personne.java, puis lancez Verifier.");
}
}
The core exercise is validated in the workshop, which requires JavaScript.
Hint 1
private forbids access from outside the class: it is the class itself that guarantees its data remain valid. That is the whole point of the filter in setAge.