Comment vérifier si un objet est une instance d'une classe en Java

JavaJavaBeginner
Pratiquer maintenant

💡 Ce tutoriel est traduit par l'IA à partir de la version anglaise. Pour voir la version originale, vous pouvez cliquer ici

Introduction

Dans ce laboratoire (lab), vous apprendrez à vérifier si un objet est une instance d'une classe ou d'une interface spécifique en Java en utilisant le mot-clé instanceof. Nous explorerons son utilisation de base, testerons son comportement avec les sous-classes et comprendrons comment il gère les objets nuls.

Grâce à des exemples pratiques, vous acquerrez une expérience concrète dans l'utilisation de instanceof pour effectuer des vérifications de type à l'exécution, un concept fondamental en programmation orientée objet.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) java(("Java")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["Object-Oriented and Advanced Concepts"]) java/BasicSyntaxGroup -.-> java/if_else("If...Else") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("Classes/Objects") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("OOP") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/inheritance("Inheritance") subgraph Lab Skills java/if_else -.-> lab-560010{{"Comment vérifier si un objet est une instance d'une classe en Java"}} java/classes_objects -.-> lab-560010{{"Comment vérifier si un objet est une instance d'une classe en Java"}} java/oop -.-> lab-560010{{"Comment vérifier si un objet est une instance d'une classe en Java"}} java/inheritance -.-> lab-560010{{"Comment vérifier si un objet est une instance d'une classe en Java"}} end

Utiliser instanceof pour vérifier la classe

Dans cette étape, nous allons explorer le mot-clé instanceof en Java. Le mot-clé instanceof est utilisé pour tester si un objet est une instance d'une classe particulière ou implémente une interface particulière. C'est un outil utile pour vérifier le type d'un objet à l'exécution.

Créons un simple programme Java pour démontrer le fonctionnement de instanceof.

  1. Ouvrez l'WebIDE et assurez-vous que vous êtes dans le répertoire ~/project. Vous pouvez le confirmer en regardant l'invite de commande du terminal ou en tapant pwd puis en appuyant sur Entrée.

  2. Créez un nouveau fichier Java nommé TypeCheck.java dans le répertoire ~/project. Vous pouvez le faire en cliquant avec le bouton droit dans l'explorateur de fichiers à gauche et en sélectionnant "Nouveau fichier", puis en tapant TypeCheck.java.

  3. Ouvrez le fichier TypeCheck.java dans l'éditeur et collez le code suivant :

    class Animal {
        // Base class
    }
    
    class Dog extends Animal {
        // Subclass of Animal
    }
    
    class Cat extends Animal {
        // Subclass of Animal
    }
    
    public class TypeCheck {
        public static void main(String[] args) {
            Animal myAnimal = new Dog();
    
            // Check if myAnimal is an instance of Dog
            if (myAnimal instanceof Dog) {
                System.out.println("myAnimal is an instance of Dog");
            } else {
                System.out.println("myAnimal is not an instance of Dog");
            }
    
            // Check if myAnimal is an instance of Cat
            if (myAnimal instanceof Cat) {
                System.out.println("myAnimal is an instance of Cat");
            } else {
                System.out.println("myAnimal is not an instance of Cat");
            }
    
            // Check if myAnimal is an instance of Animal
            if (myAnimal instanceof Animal) {
                System.out.println("myAnimal is an instance of Animal");
            } else {
                System.out.println("myAnimal is not an instance of Animal");
            }
        }
    }

    Dans ce code :

    • Nous définissons une classe de base Animal et deux sous-classes Dog et Cat.
    • Dans la méthode main, nous créons une variable myAnimal de type Animal et nous lui assignons un objet Dog. Cela est possible car un Dog est un type d'Animal.
    • Nous utilisons ensuite le mot-clé instanceof pour vérifier si myAnimal est une instance de Dog, Cat et Animal.
  4. Enregistrez le fichier TypeCheck.java (Ctrl+S ou Cmd+S).

  5. Compilez le programme Java en ouvrant le terminal en bas de l'WebIDE et en exécutant la commande suivante :

    javac TypeCheck.java

    S'il n'y a pas d'erreurs, cette commande créera des fichiers TypeCheck.class, Animal.class, Dog.class et Cat.class dans le répertoire ~/project.

  6. Exécutez le programme compilé en utilisant la commande suivante :

    java TypeCheck

    Vous devriez voir une sortie similaire à ceci :

    myAnimal is an instance of Dog
    myAnimal is not an instance of Cat
    myAnimal is an instance of Animal

    Cette sortie confirme que myAnimal, qui contient un objet Dog, est effectivement une instance de Dog et également une instance de sa superclasse Animal, mais pas une instance de Cat.

Vous avez utilisé avec succès le mot-clé instanceof pour vérifier le type d'un objet en Java. Dans l'étape suivante, nous explorerons le comportement de instanceof avec les sous-classes.

Tester avec des sous-classes

Dans l'étape précédente, nous avons vu qu'un objet est considéré comme une instance de sa propre classe et également une instance de sa superclasse. Explorons plus en détail le fonctionnement de instanceof avec différents types d'objets et leurs sous-classes.

Nous allons modifier notre fichier TypeCheck.java existant pour tester instanceof avec un objet Cat.

  1. Ouvrez le fichier TypeCheck.java dans l'éditeur de l'WebIDE.

  2. Localisez la méthode main et ajoutez les lignes de code suivantes après les vérifications existantes pour myAnimal :

            System.out.println("\n--- Testing with a Cat object ---");
            Animal anotherAnimal = new Cat();
    
            // Check if anotherAnimal is an instance of Dog
            if (anotherAnimal instanceof Dog) {
                System.out.println("anotherAnimal is an instance of Dog");
            } else {
                System.out.println("anotherAnimal is not an instance of Dog");
            }
    
            // Check if anotherAnimal is an instance of Cat
            if (anotherAnimal instanceof Cat) {
                System.out.println("anotherAnimal is an instance of Cat");
            } else {
                System.out.println("anotherAnimal is not an instance of Cat");
            }
    
            // Check if anotherAnimal is an instance of Animal
            if (anotherAnimal instanceof Animal) {
                System.out.println("anotherAnimal is an instance of Animal");
            } else {
                System.out.println("anotherAnimal is not an instance of Animal");
            }

    Votre fichier TypeCheck.java complet devrait maintenant ressembler à ceci :

    class Animal {
        // Base class
    }
    
    class Dog extends Animal {
        // Subclass of Animal
    }
    
    class Cat extends Animal {
        // Subclass of Animal
    }
    
    public class TypeCheck {
        public static void main(String[] args) {
            Animal myAnimal = new Dog();
    
            // Check if myAnimal is an instance of Dog
            if (myAnimal instanceof Dog) {
                System.out.println("myAnimal is an instance of Dog");
            } else {
                System.out.println("myAnimal is not an instance of Dog");
            }
    
            // Check if myAnimal is an instance of Cat
            if (myAnimal instanceof Cat) {
                System.out.println("myAnimal is an instance of Cat");
            } else {
                System.out.println("myAnimal is not an instance of Cat");
            }
    
            // Check if myAnimal is an instance of Animal
            if (myAnimal instanceof Animal) {
                System.out.println("myAnimal is an instance of Animal");
            } else {
                System.out.println("myAnimal is not an instance of Animal");
            }
    
            System.out.println("\n--- Testing with a Cat object ---");
            Animal anotherAnimal = new Cat();
    
            // Check if anotherAnimal is an instance of Dog
            if (anotherAnimal instanceof Dog) {
                System.out.println("anotherAnimal is an instance of Dog");
            } else {
                System.out.println("anotherAnimal is not an instance of Dog");
            }
    
            // Check if anotherAnimal is an instance of Cat
            if (anotherAnimal instanceof Cat) {
                System.out.println("anotherAnimal is an instance of Cat");
            } else {
                System.out.println("anotherAnimal is not an instance of Cat");
            }
    
            // Check if anotherAnimal is an instance of Animal
            if (anotherAnimal instanceof Animal) {
                System.out.println("anotherAnimal is an instance of Animal");
            } else {
                System.out.println("anotherAnimal is not an instance of Animal");
            }
        }
    }
  3. Enregistrez le fichier TypeCheck.java modifié.

  4. Compilez le programme à nouveau dans le terminal :

    javac TypeCheck.java
  5. Exécutez le programme compilé :

    java TypeCheck

    Vous devriez maintenant voir une sortie similaire à ceci :

    myAnimal is an instance of Dog
    myAnimal is not an instance of Cat
    myAnimal is an instance of Animal
    
    --- Testing with a Cat object ---
    anotherAnimal is not an instance of Dog
    anotherAnimal is an instance of Cat
    anotherAnimal is an instance of Animal

    Cette sortie montre que anotherAnimal, qui contient un objet Cat, est une instance de Cat et Animal, mais pas de Dog. Cela renforce le concept selon lequel instanceof vérifie le type réel de l'objet et sa hiérarchie d'héritage.

Vous avez testé avec succès le mot-clé instanceof avec différents objets de sous-classes. Dans l'étape suivante, nous verrons comment instanceof se comporte avec des objets null.

Vérification avec des objets null

Dans cette étape finale, nous allons étudier le comportement du mot-clé instanceof lorsque l'objet testé est null. Comprendre ce comportement est important pour éviter les erreurs potentielles dans vos programmes Java.

Nous allons de nouveau modifier notre fichier TypeCheck.java pour inclure un test avec un objet null.

  1. Ouvrez le fichier TypeCheck.java dans l'éditeur de l'WebIDE.

  2. Ajoutez les lignes de code suivantes à la fin de la méthode main, après les tests précédents :

            System.out.println("\n--- Testing with a null object ---");
            Animal nullAnimal = null;
    
            // Check if nullAnimal is an instance of Dog
            if (nullAnimal instanceof Dog) {
                System.out.println("nullAnimal is an instance of Dog");
            } else {
                System.out.println("nullAnimal is not an instance of Dog");
            }
    
            // Check if nullAnimal is an instance of Animal
            if (nullAnimal instanceof Animal) {
                System.out.println("nullAnimal is an instance of Animal");
            } else {
                System.out.println("nullAnimal is not an instance of Animal");
            }

    Votre fichier TypeCheck.java complet devrait maintenant ressembler à ceci :

    class Animal {
        // Base class
    }
    
    class Dog extends Animal {
        // Subclass of Animal
    }
    
    class Cat extends Animal {
        // Subclass of Animal
    }
    
    public class TypeCheck {
        public static void main(String[] args) {
            Animal myAnimal = new Dog();
    
            // Check if myAnimal is an instance of Dog
            if (myAnimal instanceof Dog) {
                System.out.println("myAnimal is an instance of Dog");
            } else {
                System.out.println("myAnimal is not an instance of Dog");
            }
    
            // Check if myAnimal is an instance of Cat
            if (myAnimal instanceof Cat) {
                System.out.println("myAnimal is not an instance of Cat");
            } else {
                System.out.println("myAnimal is not an instance of Cat");
            }
    
            // Check if myAnimal is an instance of Animal
            if (myAnimal instanceof Animal) {
                System.out.println("myAnimal is an instance of Animal");
            } else {
                System.out.println("myAnimal is not an instance of Animal");
            }
    
            System.out.println("\n--- Testing with a Cat object ---");
            Animal anotherAnimal = new Cat();
    
            // Check if anotherAnimal is an instance of Dog
            if (anotherAnimal instanceof Dog) {
                System.out.println("anotherAnimal is not an instance of Dog");
            } else {
                System.out.println("anotherAnimal is not an instance of Dog");
            }
    
            // Check if anotherAnimal is an instance of Cat
            if (anotherAnimal instanceof Cat) {
                System.out.println("anotherAnimal is an instance of Cat");
            } else {
                System.out.println("anotherAnimal is an instance of Cat");
            }
    
            // Check if anotherAnimal is an instance of Animal
            if (anotherAnimal instanceof Animal) {
                System.out.println("anotherAnimal is an instance of Animal");
            } else {
                System.out.println("anotherAnimal is an instance of Animal");
            }
    
            System.out.println("\n--- Testing with a null object ---");
            Animal nullAnimal = null;
    
            // Check if nullAnimal is an instance of Dog
            if (nullAnimal instanceof Dog) {
                System.out.println("nullAnimal is an instance of Dog");
            } else {
                System.out.println("nullAnimal is not an instance of Dog");
            }
    
            // Check if nullAnimal is an instance of Animal
            if (nullAnimal instanceof Animal) {
                System.out.println("nullAnimal is an instance of Animal");
            } else {
                System.out.println("nullAnimal is not an instance of Animal");
            }
        }
    }
  3. Enregistrez le fichier TypeCheck.java modifié.

  4. Compilez le programme dans le terminal :

    javac TypeCheck.java
  5. Exécutez le programme compilé :

    java TypeCheck

    Vous devriez voir une sortie similaire à ceci :

    myAnimal is an instance of Dog
    myAnimal is not an instance of Cat
    myAnimal is an instance of Animal
    
    --- Testing with a Cat object ---
    anotherAnimal is not an instance of Dog
    anotherAnimal is an instance of Cat
    anotherAnimal is an instance of Animal
    
    --- Testing with a null object ---
    nullAnimal is not an instance of Dog
    nullAnimal is not an instance of Animal

    Comme vous pouvez le voir dans la sortie, lorsque l'objet testé avec instanceof est null, le résultat est toujours false. C'est un point crucial à retenir lors de l'utilisation de instanceof pour éviter un comportement inattendu ou des NullPointerException.

Vous avez vérifié avec succès le comportement du mot-clé instanceof avec des objets null. Cela conclut notre exploration du mot-clé instanceof.

Résumé

Dans ce laboratoire (lab), nous avons appris à utiliser le mot-clé instanceof en Java pour vérifier si un objet est une instance d'une classe spécifique ou implémente une interface particulière. Nous avons démontré son utilisation en créant un programme simple avec une classe de base et des sous-classes, puis en utilisant instanceof pour vérifier le type d'un objet à l'exécution.

Nous avons ensuite exploré le comportement de instanceof avec les sous-classes, confirmant qu'un objet est considéré comme une instance de sa propre classe ainsi que de toutes ses superclasses. Enfin, nous avons examiné le comportement de instanceof lorsqu'il est appliqué à des objets null, et nous avons compris qu'il renvoie toujours false dans de tels cas.