Einführung
In diesem Lab werden Sie lernen, wie Sie in Java überprüfen können, ob ein Objekt eine Instanz einer bestimmten Klasse oder Schnittstelle (Interface) ist, indem Sie das Schlüsselwort instanceof verwenden. Wir werden seine grundlegende Verwendung untersuchen, sein Verhalten mit Unterklassen testen und verstehen, wie es Null-Objekte behandelt.
Durch praktische Beispiele werden Sie praktische Erfahrungen in der Verwendung von instanceof für die Laufzeittypüberprüfung sammeln, einem grundlegenden Konzept der objektorientierten Programmierung.
Verwenden Sie instanceof für die Klassenprüfung
In diesem Schritt werden wir das Schlüsselwort instanceof in Java untersuchen. Das Schlüsselwort instanceof wird verwendet, um zu testen, ob ein Objekt eine Instanz einer bestimmten Klasse ist oder eine bestimmte Schnittstelle (Interface) implementiert. Es ist ein nützliches Werkzeug für die Überprüfung des Typs eines Objekts zur Laufzeit.
Erstellen wir ein einfaches Java-Programm, um zu demonstrieren, wie instanceof funktioniert.
Öffnen Sie die WebIDE und stellen Sie sicher, dass Sie sich im Verzeichnis
~/projectbefinden. Sie können dies bestätigen, indem Sie sich den Terminalprompt ansehen oderpwdeingeben und Enter drücken.Erstellen Sie eine neue Java-Datei mit dem Namen
TypeCheck.javaim Verzeichnis~/project. Sie können dies tun, indem Sie mit der rechten Maustaste im Dateiexplorer links klicken und "Neue Datei" auswählen, dannTypeCheck.javaeingeben.Öffnen Sie die Datei
TypeCheck.javaim Editor und fügen Sie den folgenden Code ein:class Animal { // Basisklasse } class Dog extends Animal { // Unterklasse von Animal } class Cat extends Animal { // Unterklasse von Animal } public class TypeCheck { public static void main(String[] args) { Animal myAnimal = new Dog(); // Überprüfen, ob myAnimal eine Instanz von Dog ist if (myAnimal instanceof Dog) { System.out.println("myAnimal is an instance of Dog"); } else { System.out.println("myAnimal is not an instance of Dog"); } // Überprüfen, ob myAnimal eine Instanz von Cat ist if (myAnimal instanceof Cat) { System.out.println("myAnimal is an instance of Cat"); } else { System.out.println("myAnimal is not an instance of Cat"); } // Überprüfen, ob myAnimal eine Instanz von Animal ist if (myAnimal instanceof Animal) { System.out.println("myAnimal is an instance of Animal"); } else { System.out.println("myAnimal is not an instance of Animal"); } } }In diesem Code:
- Wir definieren eine Basisklasse
Animalund zwei UnterklassenDogundCat. - In der
main-Methode erstellen wir eine VariablemyAnimalvom TypAnimalund weisen ihr einDog-Objekt zu. Dies ist möglich, weil einDogein Typ vonAnimalist. - Wir verwenden dann das Schlüsselwort
instanceof, um zu überprüfen, obmyAnimaleine Instanz vonDog,CatundAnimalist.
- Wir definieren eine Basisklasse
Speichern Sie die Datei
TypeCheck.java(Strg+S oder Cmd+S).Kompilieren Sie das Java-Programm, indem Sie das Terminal unten in der WebIDE öffnen und den folgenden Befehl ausführen:
javac TypeCheck.javaWenn keine Fehler auftreten, erstellt dieser Befehl die Dateien
TypeCheck.class,Animal.class,Dog.classundCat.classim Verzeichnis~/project.Führen Sie das kompilierte Programm mit dem folgenden Befehl aus:
java TypeCheckSie sollten eine Ausgabe ähnlich der folgenden sehen:
myAnimal is an instance of Dog myAnimal is not an instance of Cat myAnimal is an instance of AnimalDiese Ausgabe bestätigt, dass
myAnimal, das einDog-Objekt enthält, tatsächlich eine Instanz vonDogund auch eine Instanz seiner SuperklasseAnimalist, aber keine Instanz vonCat.
Sie haben erfolgreich das Schlüsselwort instanceof verwendet, um den Typ eines Objekts in Java zu überprüfen. Im nächsten Schritt werden wir untersuchen, wie instanceof mit Unterklassen umgeht.
Testen mit Unterklassen
Im vorherigen Schritt haben wir gesehen, dass ein Objekt sowohl als Instanz seiner eigenen Klasse als auch als Instanz seiner Superklasse betrachtet wird. Lassen Sie uns weiter untersuchen, wie instanceof mit verschiedenen Objekttypen und ihren Unterklassen funktioniert.
Wir werden unsere vorhandene TypeCheck.java-Datei ändern, um instanceof mit einem Cat-Objekt zu testen.
Öffnen Sie die
TypeCheck.java-Datei im WebIDE-Editor.Suchen Sie die
main-Methode und fügen Sie die folgenden Codezeilen nach den bestehenden Prüfungen fürmyAnimalhinzu: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"); }Ihre vollständige
TypeCheck.java-Datei sollte jetzt so aussehen: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"); } } }Speichern Sie die geänderte
TypeCheck.java-Datei.Kompilieren Sie das Programm erneut im Terminal:
javac TypeCheck.javaFühren Sie das kompilierte Programm aus:
java TypeCheckSie sollten jetzt eine Ausgabe ähnlich der folgenden sehen:
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 AnimalDiese Ausgabe zeigt, dass
anotherAnimal, das einCat-Objekt enthält, eine Instanz vonCatundAnimalist, aber nicht vonDog. Dies bestätigt das Konzept, dassinstanceofden tatsächlichen Typ des Objekts und seine Vererbungshierarchie prüft.
Sie haben erfolgreich das Schlüsselwort instanceof mit verschiedenen Unterklassenobjekten getestet. Im nächsten Schritt werden wir sehen, wie instanceof mit null-Objekten umgeht.
Mit Null-Objekten überprüfen
In diesem letzten Schritt werden wir untersuchen, wie das Schlüsselwort instanceof verhält, wenn das zu testende Objekt null ist. Das Verständnis dieses Verhaltens ist wichtig, um potenzielle Fehler in Ihren Java-Programmen zu vermeiden.
Wir werden erneut unsere TypeCheck.java-Datei ändern, um einen Test mit einem null-Objekt hinzuzufügen.
Öffnen Sie die
TypeCheck.java-Datei im WebIDE-Editor.Fügen Sie die folgenden Codezeilen am Ende der
main-Methode, nach den vorherigen Tests, hinzu: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"); }Ihre vollständige
TypeCheck.java-Datei sollte jetzt so aussehen: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"); } } }Speichern Sie die geänderte
TypeCheck.java-Datei.Kompilieren Sie das Programm im Terminal:
javac TypeCheck.javaFühren Sie das kompilierte Programm aus:
java TypeCheckSie sollten eine Ausgabe ähnlich der folgenden sehen:
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 AnimalWie Sie aus der Ausgabe sehen können, ist das Ergebnis immer
false, wenn das mitinstanceofgetestete Objektnullist. Dies ist ein wichtiger Punkt, den Sie sich merken sollten, wenn Sieinstanceofverwenden, um unerwartetes Verhalten oderNullPointerExceptions zu vermeiden.
Sie haben erfolgreich überprüft, wie das Schlüsselwort instanceof mit null-Objekten verhält. Damit ist unsere Untersuchung des Schlüsselworts instanceof abgeschlossen.
Zusammenfassung
In diesem Lab haben wir gelernt, wie man das Schlüsselwort instanceof in Java verwendet, um zu prüfen, ob ein Objekt eine Instanz einer bestimmten Klasse ist oder ein bestimmtes Interface implementiert. Wir haben seine Verwendung demonstriert, indem wir ein einfaches Programm mit einer Basisklasse und Unterklassen erstellt und dann instanceof verwendet haben, um den Typ eines Objekts zur Laufzeit zu überprüfen.
Wir haben weiter untersucht, wie instanceof mit Unterklassen interagiert und bestätigt, dass ein Objekt sowohl als Instanz seiner eigenen Klasse als auch als Instanz aller Superklassen betrachtet wird. Schließlich haben wir das Verhalten von instanceof bei der Anwendung auf Null-Objekte untersucht und verstanden, dass es in solchen Fällen immer false zurückgibt.



