Wie man prüft, ob ein Objekt eine Instanz einer Klasse in Java ist

JavaJavaBeginner
Jetzt üben

💡 Dieser Artikel wurde von AI-Assistenten übersetzt. Um die englische Version anzuzeigen, können Sie hier klicken

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.


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{{"Wie man prüft, ob ein Objekt eine Instanz einer Klasse in Java ist"}} java/classes_objects -.-> lab-560010{{"Wie man prüft, ob ein Objekt eine Instanz einer Klasse in Java ist"}} java/oop -.-> lab-560010{{"Wie man prüft, ob ein Objekt eine Instanz einer Klasse in Java ist"}} java/inheritance -.-> lab-560010{{"Wie man prüft, ob ein Objekt eine Instanz einer Klasse in Java ist"}} end

Verwenden von instanceof für die Klassenüberprü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.

  1. Öffnen Sie die WebIDE und stellen Sie sicher, dass Sie sich im Verzeichnis ~/project befinden. Sie können dies bestätigen, indem Sie sich den Terminalprompt ansehen oder pwd eingeben und Enter drücken.

  2. Erstellen Sie eine neue Java-Datei mit dem Namen TypeCheck.java im Verzeichnis ~/project. Sie können dies tun, indem Sie mit der rechten Maustaste im Dateiexplorer links klicken und "Neue Datei" auswählen, dann TypeCheck.java eingeben.

  3. Öffnen Sie die Datei TypeCheck.java im 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 Animal und zwei Unterklassen Dog und Cat.
    • In der main-Methode erstellen wir eine Variable myAnimal vom Typ Animal und weisen ihr ein Dog-Objekt zu. Dies ist möglich, weil ein Dog ein Typ von Animal ist.
    • Wir verwenden dann das Schlüsselwort instanceof, um zu überprüfen, ob myAnimal eine Instanz von Dog, Cat und Animal ist.
  4. Speichern Sie die Datei TypeCheck.java (Strg+S oder Cmd+S).

  5. Kompilieren Sie das Java-Programm, indem Sie das Terminal unten in der WebIDE öffnen und den folgenden Befehl ausführen:

    javac TypeCheck.java

    Wenn keine Fehler auftreten, erstellt dieser Befehl die Dateien TypeCheck.class, Animal.class, Dog.class und Cat.class im Verzeichnis ~/project.

  6. Führen Sie das kompilierte Programm mit dem folgenden Befehl aus:

    java TypeCheck

    Sie 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

    Diese Ausgabe bestätigt, dass myAnimal, das ein Dog-Objekt enthält, tatsächlich eine Instanz von Dog und auch eine Instanz seiner Superklasse Animal ist, aber keine Instanz von Cat.

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.

Test 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.

  1. Öffnen Sie die TypeCheck.java-Datei im WebIDE-Editor.

  2. Suchen Sie die main-Methode und fügen Sie die folgenden Codezeilen nach den bestehenden Prüfungen für myAnimal hinzu:

            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");
            }
        }
    }
  3. Speichern Sie die geänderte TypeCheck.java-Datei.

  4. Kompilieren Sie das Programm erneut im Terminal:

    javac TypeCheck.java
  5. Führen Sie das kompilierte Programm aus:

    java TypeCheck

    Sie 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 Animal

    Diese Ausgabe zeigt, dass anotherAnimal, das ein Cat-Objekt enthält, eine Instanz von Cat und Animal ist, aber nicht von Dog. Dies bestätigt das Konzept, dass instanceof den 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.

Überprüfung mit Null-Objekten

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.

  1. Öffnen Sie die TypeCheck.java-Datei im WebIDE-Editor.

  2. 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");
            }
        }
    }
  3. Speichern Sie die geänderte TypeCheck.java-Datei.

  4. Kompilieren Sie das Programm im Terminal:

    javac TypeCheck.java
  5. Führen Sie das kompilierte Programm aus:

    java TypeCheck

    Sie 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 Animal

    Wie Sie aus der Ausgabe sehen können, ist das Ergebnis immer false, wenn das mit instanceof getestete Objekt null ist. Dies ist ein wichtiger Punkt, den Sie sich merken sollten, wenn Sie instanceof verwenden, um unerwartetes Verhalten oder NullPointerExceptions 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.