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.
Utiliser instanceof pour la vérification de 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.
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 tapantpwdpuis en appuyant sur Entrée.Créez un nouveau fichier Java nommé
TypeCheck.javadans 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 tapantTypeCheck.java.Ouvrez le fichier
TypeCheck.javadans 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
Animalet deux sous-classesDogetCat. - Dans la méthode
main, nous créons une variablemyAnimalde typeAnimalet nous lui assignons un objetDog. Cela est possible car unDogest un type d'Animal. - Nous utilisons ensuite le mot-clé
instanceofpour vérifier simyAnimalest une instance deDog,CatetAnimal.
- Nous définissons une classe de base
Enregistrez le fichier
TypeCheck.java(Ctrl+S ou Cmd+S).Compilez le programme Java en ouvrant le terminal en bas de l'WebIDE et en exécutant la commande suivante :
javac TypeCheck.javaS'il n'y a pas d'erreurs, cette commande créera des fichiers
TypeCheck.class,Animal.class,Dog.classetCat.classdans le répertoire~/project.Exécutez le programme compilé en utilisant la commande suivante :
java TypeCheckVous devriez voir une sortie similaire à ceci :
myAnimal is an instance of Dog myAnimal is not an instance of Cat myAnimal is an instance of AnimalCette sortie confirme que
myAnimal, qui contient un objetDog, est effectivement une instance deDoget également une instance de sa superclasseAnimal, mais pas une instance deCat.
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.
Ouvrez le fichier
TypeCheck.javadans l'éditeur de l'WebIDE.Localisez la méthode
mainet ajoutez les lignes de code suivantes après les vérifications existantes pourmyAnimal: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.javacomplet 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"); } } }Enregistrez le fichier
TypeCheck.javamodifié.Compilez le programme à nouveau dans le terminal :
javac TypeCheck.javaExécutez le programme compilé :
java TypeCheckVous 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 AnimalCette sortie montre que
anotherAnimal, qui contient un objetCat, est une instance deCatetAnimal, mais pas deDog. Cela renforce le concept selon lequelinstanceofvé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érifier 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.
Ouvrez le fichier
TypeCheck.javadans l'éditeur de l'WebIDE.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.javacomplet 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"); } } }Enregistrez le fichier
TypeCheck.javamodifié.Compilez le programme dans le terminal :
javac TypeCheck.javaExécutez le programme compilé :
java TypeCheckVous 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 AnimalComme vous pouvez le voir dans la sortie, lorsque l'objet testé avec
instanceofestnull, le résultat est toujoursfalse. C'est un point crucial à retenir lors de l'utilisation deinstanceofpour éviter un comportement inattendu ou desNullPointerException.
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.



