Version without JavaScript, read-only: workshops, quizzes and running code are not available here. Full version · Catalogue · Sign in

Sequence

Overriding toString()

Core exercise

Add toString() to Personne (it must return "Jean Dupont (18 ans)", “ans” being French for “years old”) and override it in Etudiant to add the number: "Jean Dupont (18 ans) - 3iL2025". Then check that System.out.println(personne) directly prints the right text.

A workshop goes here: you write and run code in it. It requires JavaScript.

Starting code

Personne.java

public class Personne {

    private String nom;
    private String prenom;
    private int age;

    public Personne(String nom, String prenom, int age) {
        this.nom = nom;
        this.prenom = prenom;
        this.age = age;
    }

    public String getNom() {
        return nom;
    }

    public String getPrenom() {
        return prenom;
    }

    public int getAge() {
        return age;
    }

    // TODO : @Override public String toString() -> "Jean Dupont (18 ans)"
}

Etudiant.java

public class Etudiant extends Personne {

    private String numEtudiant;

    public Etudiant(String nom, String prenom, int age, String numEtudiant) {
        super(nom, prenom, age);
        this.numEtudiant = numEtudiant;
    }

    public String getNumEtudiant() {
        return numEtudiant;
    }

    // TODO : @Override public String toString() avec super.toString() + " - " + numEtudiant
}

Exercices.java

public class Exercices {

    public static void main(String[] args) {
        System.out.println(new Personne("Dupont", "Jean", 18));
        System.out.println(new Etudiant("Dupont", "Jean", 18, "3iL2025"));
    }
}

The core exercise is validated in the workshop, which requires JavaScript.

Hint 1

toString() is called automatically as soon as an object is concatenated or printed. In Etudiant, reuse the parent’s work with super.toString() instead of rewriting everything. The @Override annotation asks the compiler to check that you are indeed overriding an existing method.